简体   繁体   中英

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

Is there a way to have a little separation between each group bars made with grouped bar_plot() ? Like having a bigger distance between different groups and small distance inside group bars, but not sticked one another.

Here the whole code:

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

my result:

粘条

what I'd like to get (ignore colors difference etc, only for the bars positions):

分隔条

Thanks in advance for any help!

You can adjust these with the width parameters of geom_bar and position_dodge .

geom_bar 's width controls how wide each individual bar is. If = 1 , the bars will collectively be as wide as the whole x-axis. (Though there may be space between groups if the bars overlap with each group.)

position_dodge 's width controls how much space each group is given. If it's zero, the bars in each group will be fully overlapped. If it matches the geom_bar width , the bars in each group will be touching each other on the sides. If it's 1, the distance between groups will be the same as the distance inside each group.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM