gpt4 book ai didi

R ggplot2 - geom_histogram : levels/color removed in plot due to limiting y-scale

转载 作者:行者123 更新时间:2023-12-04 07:39:14 25 4
gpt4 key购买 nike

我每年都有一定数量的不同患者属于三个级别之一。我想绘制每年三个级别的相对频率分布。假设 80% 的患者被标记为 C,另一名患者被标记为 A 和 B。由于大多数患者具有 C,因此 A 和 B 的分布将不可见。所以,我改变了y轴。我在使用 ggplot 时遇到了以下问题:显示了 A 和 B 的彩色列,但对于 C,它从图中消失了。
这里我举了一个例子:

library(ggplot2)
# Data set
grp <- rep(c("A","B","C"), c(10,10,80))
year <- floor(runif(100)*10/3)
df <- data.frame(grp,year)
# Plot
ggplot(df,aes(year)) +
geom_histogram(aes(fill=grp),position="fill") +
scale_y_continuous(lim=c(0,0.5))

如果我删除最后一行 (scale_y...),那么我会得到从 0 到 1 的整个范围,并显示所有级别(颜色)。随着 scale_y.. 级别(颜色)C 消失,只有灰色背景可见。有谁知道如何避免 C 的颜色消失?谢谢你的提示。

最佳答案

正如@Harpal 在您在 scale_y_continuous() 中设置限制时已经说过的那样超出此限制的所有值都将从图中删除。如果您需要将绘图“缩放”到 0 到 0.5 之间的值,请使用 coord_cartesian()而不是 scale_y_continuous() .

ggplot(df,aes(year)) +  
geom_histogram(aes(fill=grp),position="fill") +
coord_cartesian(y=c(0,0.5))

enter image description here

关于R ggplot2 - geom_histogram : levels/color removed in plot due to limiting y-scale,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17211484/

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