简体   繁体   English

每个栏的宽度不同,在ggplot2中使用geom_bar和“position = fill”

[英]different width for each bar, using geom_bar with “position=fill” in ggplot2

could you tell me if it is possible make a bar plot with bar height normalized to 1, but bar width proportional to the number of elements in each bin. 你能告诉我是否可以制作条形高度标准化为1的条形图,但是条形宽度与每个区域中的元素数量成比例。

Example : this plot 示例:此图

ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) + geom_bar(position="fill")

and then make the width of the 3 bars proportional to 然后使3个条的宽度成比例

table(factor(mtcars$cyl))

There is well that "width" parameter in position_fill() but it has to be a constant, hasn't it ? 在position_fill()中有“width”参数,但它必须是常量,不是吗?

Thank you, 谢谢,

François 弗朗索瓦

EDIT : 编辑:

I tried a bit further, and get the message : "position_fill requires constant width" 我试了一下,得到消息:“position_fill需要恒定的宽度”

So I guess to get what I tried to get is impossible, at least using geom_bar. 所以我想要得到我想要的东西是不可能的,至少使用geom_bar。

I can do it by preprocessing the data, but not entirely within a single ggplot call. 我可以通过预处理数据来完成,但不是完全在单个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)

The mt data set now has everything needed to make the plot: 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

and the ggplot call would look like 并且ggplot调用看起来像

ggplot(mt, aes(x=factor(cyl), fill=factor(vs), y=nfrac)) +
  geom_bar(aes(width=width), position="stack", stat="identity")

It does throw the warning: 它确实抛出警告:

Warning message:
position_stack requires constant width: output may be incorrect 

but creates the plot: 但创造了情节:

在此输入图像描述

Is this what you want? 这是你想要的吗?

library(ggplot2)
ggplot(mtcars, aes(x=factor(cyl), fill=factor(vs))) + geom_bar(position="fill") + coord_flip()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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