ggplot 各组百分比的条形图 [英] ggplot bar chart of percentages over groups
问题描述
如果我执行以下命令
数据(mtcars)ggplot(data=mtcars, aes(cyl))+geom_bar(aes(fill=as.factor(gear), y = (..count..)/sum(..count..)), position="dodge") +scale_y_continuous(标签=百分比)
我会得到
然而,我真正想做的是让每个 gear
级别加起来为 100%.所以,gear
是我正在查看的子组,我想知道每个组内的分布.
我不想使用 facets
并且我也不想融化数据.有没有办法做到这一点?
首先:你的代码对我来说是不可重现的(即使在包含 library(ggplot2)
之后也是如此).我不确定 ..count..
是否是一种我不知道的花哨语法,但无论如何,如果我能够立即重现它会更好:-).
话虽如此,我认为您正在寻找的内容在
这是您要找的吗?
<小时>事后思考:必须学习 melt()
或其替代方案.但是,reshape2
中的 melt()
在大多数用例中是通过 tidyr
包中的 gather()
成功的.
If I do the following command
data(mtcars)
ggplot(data=mtcars, aes(cyl))+
geom_bar(aes(fill=as.factor(gear), y = (..count..)/sum(..count..)), position="dodge") +
scale_y_continuous(labels=percent)
I will get
However, what I really want to do is have each of the gear
levels add up to 100%. So, gear
is the subgroup I am looking at, and I want to know the distribution within each group.
I don't want to use facets
and I don't want to melt the data either. Is there a way to do this?
First of all: Your code is not reproducible for me (not even after including library(ggplot2)
). I am not sure if ..count..
is a fancy syntax I am not aware of, but in any case it would be nicer if I would have been able to reproduce right away :-).
Having said that, I think what you are looking for it described in http://docs.ggplot2.org/current/geom_bar.html and applied to your example the code
library(ggplot2)
data(mtcars)
mtcars$gear <- as.factor(mtcars$gear)
ggplot(data=mtcars, aes(cyl))+
geom_bar(aes(fill=as.factor(gear)), position="fill")
produces
Is this what you are looking for?
Afterthought: Learning melt()
or its alternatives is a must. However, melt()
from reshape2
is succeeded for most use-cases by gather()
from tidyr
package.
这篇关于ggplot 各组百分比的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!