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

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

我使用ggplot2在R中有一个条形图,它显示了不同类别的不同条形图。因为某些条形码= 0,我想在不同类别之间建立一条垂直线,以便在视觉上更好地区分它们。

我已经尝试通过panel.grid.major.xpanel.grid.minor.x参数添加它,但这不起作用。如果我可以使用widthgeom_bar参数更改不同类别的条形之间的距离而不是所有类别,这也许会有所帮助

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

Example plot

这是我的代码:

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在不同类别之间添加垂直线和空格?

r ggplot2 geom-bar
1个回答
1
投票

使用position_dodge参数到你的geom。我在这里选择一个更小的例子,但你应该能够从那里推广它。

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()

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