0

R: I have found that when trying to plot an overlay of a histogram with geom_area, the result of individual overlays isn't consistent with when they are plotted together. Case in point:

#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))))

To illustrate my point, I sort the data into either F or M then plot histogram and geom_area of each.

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

Result of blue

Result of red

But when I plot both sets of data together, the red geom_area overlay is different - it seems to be taking the data from both M and F. What do I need to change to get the red geom_area to look the same as when it is plotted by itself?

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

Red and blue

JREN_OP
  • 79
  • 2

1 Answers1

0
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

Adding position = "identity" to geom_area fixes this issue.

JREN_OP
  • 79
  • 2