我想制作一个带有堆积条形图的图,并向右移动50%,以便刻度位于条形图之间。
library(tidyverse)
df <- tribble(~Station, ~Direction1, ~Direction2,
"A", 432, 485,
"V", 543, 345,
"B", 435, 457,
"Q", 0, 0)
df$Station <- factor(df$Station, levels=unique(df$Station))
df = gather(df, Direction1, Direction2, key = "Direction", value = "Passengers")
第一张图显示了所需的堆积条形图:
ggplot(data = df, aes(x = Station, y = Passengers, fill = Direction)) +
geom_bar(stat = "identity", position = position_stack())
第二个图将条形图移动到刻度线之间的中间位置,但条形图现在彼此之间绘制在一起:
ggplot(data = df, aes(x = Station, y = Passengers, fill = Direction)) +
geom_bar(stat = "identity", position = position_nudge(x = 0.5))
如何结合两个定位命令?
以下应满足您的目的。您不必指定的位置,如果你想position_stack()
,因为它是在默认位置参数geom_bar
/ geom_col
。
(顺便说一下,您可能要考虑从切换geom_bar
为geom_col
,因为stat = "identity"
默认情况下后者使用。键入较少。)
ggplot(data = df,
aes(x = as.numeric(Station) + 0.5, y = Passengers, fill = Direction)) +
geom_col() +
scale_x_continuous(name = "Station",
limits = range(as.numeric(df$Station)),
breaks = unique(sort(as.numeric(df$Station))),
labels = levels(df$Station))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句