ggplot2:结合定位命令position_nudge和position_stack

时间:2019-04-17 15:02:49

标签: r ggplot2 position

我想制作一个带有堆叠条形图的图,并向右移动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))

如何结合两个定位命令?

1 个答案:

答案 0 :(得分:2)

以下内容可以满足您的目的。如果需要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))

this