ggplot2中的宽度相同? [英] same bar width in ggplot2?

查看:134
本文介绍了ggplot2中的宽度相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中:

  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)

因子 4 比其他柱线宽。有没有办法使它们的宽度都一样?

解决方案

理想情况下,即使数据为零。这意味着,在数据$ a中有1个,你应该有数据全部四个(A,B,C,D)等等......尝试修改你的数据框就像这样和情节。 NA类别在这里被称为其他。

  library(ggplot2)
dat < - data.frame (a =因子(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, 其他, A, b, C, d, 其他, A, B,C,D,其他,A,B,C,D,其他, 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)

查看这个数据框你会知道区别。你显然会缺少与你的数据相对应的条,这看起来不错。但恐怕这可能是唯一的解决方案。


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?

解决方案

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.

这篇关于ggplot2中的宽度相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆