ggplot2:x轴刻度之间的条形图

3
我需要可视化的数据包含了4个车站之间的乘客负载。数据是按顺序提供的,例如,在A站和V站之间有432名乘客在火车上,在V站和B站之间有543名乘客等等。在编程示例中,我使用ggplot2绘制了这些数据。
library(tidyverse)

df <- tribble(~Station, ~Passengers,
              "A", 432,
              "V", 543,
              "B", 435,
              "Q", 0)

df$Station <- factor(df$Station, levels=unique(df$Station))

ggplot(data = df, aes(x = Station, y = Passengers)) + 
  geom_bar(stat = "identity")

enter image description here

问题: 我希望将x轴刻度和站点名称放置在柱状图中间。目标是将柱状图向右移动50%。

看一下nudge函数。 - Wil
2个回答

3
我们可以使用position_nudge来调整条形图的位置:
ggplot(data = df, aes(x = Station, y = Passengers)) + 
  geom_bar(stat = "identity", position = position_nudge(x = 0.5))

enter image description here


我知道答案会非常简短!谢谢。 - flo
你已经完成了困难的部分——将因子按正确顺序排列,并包含“缺失”的级别。 - Gregor Thomas
有没有办法同时使用定位命令 position_nudge 和 position_stack?我还没有找到任何有用的信息... 我可能应该提交一个新问题。 - flo
是的,听起来像是一个新问题。我不知道如何立即解决它。 - Gregor Thomas

0

使用最新版本的ggplot 3.4.0,您可以在geom_col或geom_bar中使用以下参数:

用于列位置调整。默认值为0.5,表示列将围绕轴断点居中。将其设置为0或1可将列放置在轴断点的左侧/右侧。请注意,当与替代位置(例如position_dodge())一起使用时,此参数可能会产生意外行为。

这是一个可重现的示例:

library(tidyverse)

df <- tribble(~Station, ~Passengers,
              "A", 432,
              "V", 543,
              "B", 435,
              "Q", 0)

df$Station <- factor(df$Station, levels=unique(df$Station))

ggplot(data = df, aes(x = Station, y = Passengers)) + 
  geom_bar(stat = "identity", just = 1.05)

本文于2022年11月9日使用reprex v2.0.2创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接