R 结合直方图和;“分类”;x变量图

R 结合直方图和;“分类”;x变量图,r,ggplot2,R,Ggplot2,我想将一个二元变量的“正常”直方图(y轴上有分数)与第二个直方图(最好通过其alpha值(透明度)与第一个直方图区分)结合起来,后者描述x轴的特定类别 有关示例,请参见以下代码: ggplot(mtcars, aes(x = mpg, y = ..count../sum(..count..))) + geom_histogram() 对于数值x变量,我创建因子变量: mtcars$mpgCat <- ifelse(mtcars$mpg <= 15, 0,

我想将一个二元变量的“正常”直方图(y轴上有分数)与第二个直方图(最好通过其alpha值(透明度)与第一个直方图区分)结合起来,后者描述x轴的特定类别

有关示例,请参见以下代码:

ggplot(mtcars, aes(x = mpg, y = ..count../sum(..count..))) +
geom_histogram()
对于数值x变量,我创建因子变量:

mtcars$mpgCat <- ifelse(mtcars$mpg <= 15, 0,
                    ifelse(mtcars$mpg > 15 & mtcars$mpg <=25, 1,
                           ifelse(mtcars$mpg > 25 & mtcars$mpg < 35, 2, NA)))
mtcars$mpgCat <- factor(mtcars$mpgCat, levels = c(0:2), labels = c("<=15", ">15", "<35"))
是否有某种方法将两个直方图结合起来,最好是后者是透明的,以便数字x值直接与因子变量的相应条重叠?当然,如果因子变量的条形图的宽度代表它们“代表”的数值x变量的分数,那将是最好的。然而,后者可能过于复杂


提前感谢。

事实证明,如果您知道如何提问,ggplot2可以自动完成大部分您想要的功能。我创建了两个直方图层。第一个具有手动选择的箱子数量(
bins=10
),并手动调整
boundary=0.25
,以使箱子边界在视觉上对齐。第二个已手动创建精确的仓位边界(
breaks=c(10,15,25,35)
),以精确匹配三类
mpgCat
。它还为整个层设置了透明度(
alpha=0.4
)。您可能还对用于将连续变量拆分为因子的
cut()
函数感兴趣

library(ggplot2)

mtcars$mpgCat = cut(mtcars$mpg, c(10, 15, 25, 35))

p = ggplot(data=mtcars) +
    geom_histogram(aes(x=mpg, y=..count../sum(..count..)), 
                   bins=20, boundary=0.25) +
    geom_histogram(aes(x=mpg, y =..count../sum(..count..), fill=mpgCat), 
                   alpha=0.4, breaks=c(10, 15, 25, 35))

ggsave("histgram.png", plot=p, height=4, width=6, dpi=150)

请注意,此图可能会产生误导;红色和蓝色条分别代表20%的数据,但蓝色条的面积是红色条的两倍

我认为一种方法是尝试使用
binwidth
,例如:
ggplot(mtcars,aes(x=mpg,y=count../sum(…count..))+geom_直方图(binwidth=10,fill='blue')+geom_直方图()
library(ggplot2)

mtcars$mpgCat = cut(mtcars$mpg, c(10, 15, 25, 35))

p = ggplot(data=mtcars) +
    geom_histogram(aes(x=mpg, y=..count../sum(..count..)), 
                   bins=20, boundary=0.25) +
    geom_histogram(aes(x=mpg, y =..count../sum(..count..), fill=mpgCat), 
                   alpha=0.4, breaks=c(10, 15, 25, 35))

ggsave("histgram.png", plot=p, height=4, width=6, dpi=150)