有冗余级别时,如何在R的ggplot2中保持宽度恒定的条形图? [英] How do I keep a constant width bar chart in R's ggplot2 when there are redundant levels?
问题描述
考虑一些没有发生水平的样本数据:
Consider some sample data where a level does not occur:
dat <- data.frame(sex = c("F","M","F"),
status = c("Pregnant","Not pregnant","Not pregnant"),
frequency = c(25,100,75))
在样本数据中,男性无法怀孕,因此他们没有数据.
In the sample data males cannot become pregnant so they have no data.
我想使用以下代码在R
中的ggplot2
中绘制数据:
I would like to plot the data using ggplot2
in R
using this code:
library(ggplot2)
p <- ggplot(dat,aes(x=status,y=frequency,fill=sex))+
geom_bar(stat = "identity",position="dodge")
print(p)
我得到以下输出:
如您所见,女性和孕妇的条形图比其他条形图宽.我的问题是如何抑制条形加宽以使条形具有相同的宽度?
As you can see, the bar for female and pregnant is wider than the other bars. My question is how can I suppress the bar widening to have the bars the same width?
推荐答案
#默认情况下,闪避保留总宽度.您可以选择
# By default, dodging preserves the total width. You can choose
#保留每个元素的宽度:
# to preserve the width of each element:
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar(position = position_dodge(preserve = "single"))
来自position_dodge
的文档: http://ggplot2.tidyverse.org/reference/position_dodge.html
但是我特别喜欢这个解决方案: https://stackoverflow.com/a/38103511/3330437
But I particularly like this solution: https://stackoverflow.com/a/38103511/3330437
这篇关于有冗余级别时,如何在R的ggplot2中保持宽度恒定的条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!