首页 > 解决方案 > 绘制具有多个级别的数据时,geom_area 未显示预期结果

问题描述

R:我发现当尝试使用 geom_area 绘制直方图的叠加时,单个叠加的结果与将它们绘制在一起时的结果不一致。一个例子:

#Make data
set.seed(1234)
df <- data.frame(
  Condition=factor(rep(c("F", "M"), each=200)),
  Measurement=round(c(rnorm(200, mean=55, sd=3),
                 rnorm(200, mean=65, sd=3))))

为了说明我的观点,我将数据分类为 F 或 M,然后绘制每个的直方图和 geom_area。

df_blue <- filter(df, Condition=="M")

blue <- ggplot(df_blue, aes (x=Measurement,y=stat(ncount), color = Condition))+
  geom_histogram(fill = "white",binwidth = 1, alpha = 0.5,position="identity")+
  xlim(c(45,75))+
  ylim(c(0,1.25))+
  scale_color_manual(values=c("blue"))+
  geom_area(stat = "bin",alpha = 0.25,fill="grey",binwidth=3)

blue 

df_red <- filter(df, Condition=="F")

red <- ggplot(df_red, aes (x=Measurement,y=stat(ncount), color = Condition))+
  geom_histogram(fill = "white",binwidth = 1, alpha = 0.5,position="identity")+
  xlim(c(45,75))+
  ylim(c(0,1.25))+
  scale_color_manual(values=c("red"))+
  geom_area(stat = "bin",alpha = 0.25,fill="grey",binwidth=3)

red

蓝色的结果

红色的结果

但是当我将两组数据绘制在一起时,红色 geom_area 叠加层是不同的 - 它似乎从 M 和 F 获取数据。我需要更改什么才能让红色 geom_area 看起来与绘制时相同通过它自己?

graph <- ggplot(df, aes (x=Measurement,y=stat(ncount), color = Condition))+
  geom_histogram(fill = "white",binwidth = 1, alpha = 0.5,position="identity")+
  xlim(c(45,75))+
  ylim(c(0,1.25))+
  scale_color_manual(values=c("red","blue"))+
  geom_area(stat = "bin",alpha = 0.25,fill="grey",binwidth=3)

graph

红色和蓝色

标签: rggplot2geom-area

解决方案


graph <- ggplot(df, aes (x=Measurement,y=stat(ncount), color = Condition))+
  geom_histogram(fill = "white",binwidth = 1, alpha = 0.5,position="identity")+
  xlim(c(45,75))+
  ylim(c(0,1.25))+
  scale_color_manual(values=c("red","blue"))+
  geom_area(stat = "bin",alpha = 0.25,fill="grey",binwidth=3,position="identity")

graph

将 position = "identity" 添加到 geom_area 可解决此问题。


推荐阅读