ggplot2:组合定位命令position_nudge和position_stack

问题描述 投票:2回答:1

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

如何组合2个定位命令?

r ggplot2 position
1个回答
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))

plot

© www.soinside.com 2019 - 2024. All rights reserved.