same bar width in ggplot2? [duplicate]

2019-07-18 02:41发布

This question already has an answer here:

In this example:

library(ggplot2)
dat <- data.frame(a=factor(c(1,1,1,2,2,2,3,3,3,4)), b=c("A","B","D","A","B","C","A","B","D",NA), c=c(1,4,3,5,5,1,2,2,8,6))
plot <- ggplot(dat,aes(fill=b,x=a,y=c))
plot + geom_bar(width=.7, position=position_dodge(width=.7), stat = "identity")

factor 4 is wider than the other bars. Is there a way to make them all the same width?

标签: r ggplot2
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-18 03:15

Ideally you should have data for every combination even if it is zero. That means, with 1 in data$a you should have data all the four(A,B,C,D) and so on... try modifying your data frame like this and plot. NA category was referred to as "other" here.

library(ggplot2)
dat <- data.frame(a=factor(c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4)),
                  b=c("A","B","C","D","other","A","B","C","D","other","A","B","C","D","other","A","B","C","D","other"), 
                  c=c(1,4,0,3,0,5,5,1,0,0,2,2,0,8,0,0,0,0,0,6))
plot <- ggplot(dat,aes(fill=b,x=a,y=c))
plot + geom_bar(width=.7, position=position_dodge(width=.7), stat = "identity")

View this dataframe you will know the difference. You will obviously have missing bars corresponding to your data, which dnt look good. But im afraid this might be the only solution.

a

查看更多
登录 后发表回答