在 R 中的 ggplot2 中使用 geom_bar 图创建 space 和类别之间的垂直线

Create space and a vertical line between categories using geom_bar plot in ggplot2 in R

我在 R 中有一个使用 ggplot2 的条形图,它显示了不同类别的不同条形图。因为有些bar是=0的,所以想在不同的类别之间做一条竖线,这样可以更好的从视觉上区分。

我已经尝试通过 panel.grid.major.xpanel.grid.minor.x 参数添加它,但这没有用。当我使用 geom_bar

width 参数更改不同类别的条形之间的距离而不是所有条形之间的距离时,这可能也会有所帮助

例如。在下图中:我想在Cat 3的紫色条(Class 5)和Cat 4的蓝色条(Class 1)之间添加一条垂直线和space。

这是我的代码:

data <- categories.df
ggplot(data, aes(factor(Name, levels = c("Cat 1", "Cat 2", "Cat 3", "Cat 4", "Cat 5")), Count, fill = factor(SC_Class, levels = c("Class 1", "Class 2", "Class 3", "Class 4", "Class 5")))) +
    geom_bar(stat = "identity", position = position_dodge(width = 1), width = 0.8) +
    scale_fill_manual(values = c("#6C8EBF", "red", "#74767a", "orange","purple")) +
    labs(fill = "") +
    ylim(0,25) +
    xlab("Category") + ylab("Count") +
    theme(legend.position = c(1,1), legend.justification = c(1,1),
          axis.text.x = element_text(face = "bold", size=14),
          axis.text.y = element_text(face = "bold", size=14),
          axis.title.x = element_text(colour = "#6C8EBF", face = "bold", size =16),
          axis.title.y = element_text(colour = "#6C8EBF", face = "bold", size =16),
          panel.grid.major.y = element_line(size = 1, colour="#DAE8FC"),
          panel.grid.minor.y = element_line(colour="#DAE8FC"),
          panel.grid.major.x = element_blank(),
          panel.grid.minor.x = element_line(size = 1, colour="#DAE8FC"),
          plot.background = element_blank(),
          panel.background = element_blank(),
          panel.border = element_blank(),
          legend.text = element_text(size=12, face="bold")) 

如何使用 R 中的 ggplot2 在不同类别之间添加垂直线和 spaces?

对您的 geom 使用 position_dodge 参数。我在这里选择了一个更小的例子,但你应该能够从那里概括它。

test <- data.frame(
  a=1:9,
  b=rep(letters[1:3], 3),
  c=rep(letters[1:3], each=3)
)

ggplot(test, aes(y=a, x=b, group=c, fill=c)) + 
  geom_col(position="dodge") +
  geom_vline(xintercept = 1.5)

(基于这个答案:ggplot side by side geom_bar()