使用 ggplot2 geom_bar() 绘制稍微分开的组内条形图

plot slightly separated in-group bars with ggplot2 geom_bar()

有没有办法在分组 bar_plot() 的每个组条之间有一点分隔?就像不同组之间的距离更大,组内的距离更小,但又不粘在一起。

这里是完整的代码:

### my DF generation
df.bar <- as.data.frame( cbind(
                                "diagnosis" = rep( names_DX, 2 ) ,
                                "number" = as.numeric(c(9,18,43,8,34,12,3,7,38,12,8,6)),
                                "status" = c(1,1,1,1,1,1,0,0,0,0,0,0)
                                ))
df.bar$diagnosis <- factor(df.bar$diagnosis,levels(df.bar$diagnosis)[c(1,5,6,2:4)]) #reorder levels for plot

### plot generation
p <-    ggplot(data = df.bar, aes(x = diagnosis, y = as.numeric(as.character(number)), fill = factor(status) )) +
            geom_bar(stat = "identity", position=position_dodge())+
            theme_bw()

我的结果:

我想得到什么(忽略颜色差异等,仅针对条形位置):

在此先感谢您的帮助!

您可以使用 geom_barposition_dodgewidth 参数进行调整。

geom_barwidth 控制每个条的宽度。如果 = 1,条形的总和将与整个 x-axis 一样宽。 (尽管如果条形图与每个组重叠,则组之间可能 space。)

position_dodgewidth 控制每个组的分配量 space。如果它为零,则每组中的条将完全重叠。如果它匹配 geom_bar width,每组中的条将在两侧相互接触。如果为1,则组间距离将与组内距离相同。

library(ggplot2)
ggplot(data = df.bar, aes(x = diagnosis, y = as.numeric(as.character(number)), fill = factor(status) )) +
  geom_bar(stat = "identity",  width = 0.4,
           position=position_dodge(width = 0.5))+
  theme_bw()