fst*_*ens 4 r bar-chart ggplot2
你能告诉我是否可以制作一个条形图,其条形高度归一化为 1,但条形宽度与每个 bin 中的元素数量成正比。
\n\n示例:这个图
\n\nggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) + geom_bar(position="fill")\nRun Code Online (Sandbox Code Playgroud)\n\n然后使 3 个条形的宽度与
\n\ntable(factor(mtcars$cyl))\nRun Code Online (Sandbox Code Playgroud)\n\nposition_fill() 中有一个“width”参数,但它必须是一个常量,不是吗?
\n\n谢谢你,
\n\n弗朗西斯·xc3·xa7ois
\n\n编辑 :
\n\n我进一步尝试,并收到消息:“position_fill 需要恒定宽度”
\n\n所以我想得到我想要得到的东西是不可能的,至少使用 geom_bar 是不可能的。
\n我可以通过预处理数据来做到这一点,但不能完全在一次ggplot调用中完成。
library("plyr")
mt <- ddply(mtcars, .(cyl, vs), summarise, n=length(cyl))
mt <- ddply(mt, .(cyl), mutate, nfrac = n/sum(n), width = sum(n))
mt$width <- mt$width / max(mt$width)
Run Code Online (Sandbox Code Playgroud)
数据mt集现在拥有绘制绘图所需的一切:
> mt
cyl vs n nfrac width
1 4 0 1 0.09090909 0.7857143
2 4 1 10 0.90909091 0.7857143
3 6 0 3 0.42857143 0.5000000
4 6 1 4 0.57142857 0.5000000
5 8 0 14 1.00000000 1.0000000
Run Code Online (Sandbox Code Playgroud)
通话ggplot看起来像
ggplot(mt, aes(x=factor(cyl), fill=factor(vs), y=nfrac)) +
geom_bar(aes(width=width), position="stack", stat="identity")
Run Code Online (Sandbox Code Playgroud)
它确实会发出警告:
Warning message:
position_stack requires constant width: output may be incorrect
Run Code Online (Sandbox Code Playgroud)
但创造了情节:
