gpt4 book ai didi

r - 当存在冗余级别时,如何在 R 的 ggplot2 中保持恒定宽度的条形图?

转载 作者:行者123 更新时间:2023-12-04 10:36:55 24 4
gpt4 key购买 nike

考虑一些不出现级别的示例数据:

dat <- data.frame(sex = c("F","M","F"),
status = c("Pregnant","Not pregnant","Not pregnant"),
frequency = c(25,100,75))

在样本数据中,男性无法怀孕,因此他们没有数据。

我想使用 ggplot2 绘制数据在 R使用此代码:
library(ggplot2)

p <- ggplot(dat,aes(x=status,y=frequency,fill=sex))+
geom_bar(stat = "identity",position="dodge")

print(p)

我得到这个输出:

enter image description here

如您所见,女性和孕妇的栏比其他栏更宽。我的问题是 如何抑制条形加宽以使条形具有相同的宽度?

最佳答案

# 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"))
enter image description here
来自 position_dodge 的文档: http://ggplot2.tidyverse.org/reference/position_dodge.html
但我特别喜欢这个解决方案:
https://stackoverflow.com/a/38103511/3330437

关于r - 当存在冗余级别时,如何在 R 的 ggplot2 中保持恒定宽度的条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com