Home > Mobile >  How to overplot geom_histogram with stat_bin or geom_line with multiple groupings?
How to overplot geom_histogram with stat_bin or geom_line with multiple groupings?

Time:05-28

I'm trying to create a plot which has:

  1. histogram of values in "historic" time period, created from method "A"
  2. histogram of values in "future" time period, created from method "A"
  3. either stat_bin or geom_line of values in both "historic" and "future" time period, created from method "B"

example data:

draw method Parameter Value
1 A historic 0.99
1 A future 0.98
1 B historic 0.97
1 B future 0.96
2 A historic 0.9
2 A future 0.88
2 B historic 0.95
2 B future 0.94
3 A historic 0.97
3 A future 0.94
3 B historic 0.91
3 B future 0.89

  ggplot(df,aes(x=Value,color=Parameter,fill=Parameter))   
  scale_color_discrete(name="Period",labels=c("historic","future"))  
  scale_fill_discrete(name="Period",labels=c("historic","future"),guide="none")  
  geom_histogram(aes(y=..density..),
    breaks=seq(.8,1.0,by=0.01),
    alpha=0.4,position="identity")   
  theme(axis.title.x=element_blank(),axis.text.x=element_blank(),
  axis.title.y=element_blank())  
  scale_x_continuous(breaks=seq(.8,1.00,by=0.01))  coord_flip()  
  theme(legend.position = "bottom")  
  geom_line(data=subset(df,method == "B"),
    aes(x=Value),stat="density")

In the image, it looks like the histogram is plotting all of the "method" values. But in the histograms, I only want method == "A" (and Parameter == "historic" and "future"). Is there any way to create different types of plots based on two types of groupings? The geom_line should only be plotting method == "B", Parameter == "historic","future", and geom_histogram should only be plotting , method == "A", Parameter == "historic","future".

enter image description here

I'd like the final result to look like this: (either the left, with geom_line, or the right, with stat_bin)

enter image description here

CodePudding user response:

Plotting what you requested, i.e. histogram bars from method "A" and line from method "B".

Reading in example data:

x <- '
draw method Parameter Value
1 A historic 0.99
1 A future 0.98
1 B historic 0.97
1 B future 0.96
2 A historic 0.9
2 A future 0.88
2 B historic 0.95
2 B future 0.94
3 A historic 0.97
3 A future 0.94
3 B historic 0.91
3 B future 0.89
'

df <- read.table(textConnection(x), header = TRUE)

Plotting:

 ggplot()  
  geom_histogram(data=df %>% filter(method=="A"),
                 aes(x=Value, y=..density.., fill=Parameter),
                 breaks=seq(.8, 1.0, by=0.01),
                 alpha=0.4, position="identity")  
  geom_line(data=df %>% filter(method=="B"),
            aes(x=Value, colour=Parameter), stat="density")  
  scale_fill_discrete(name="", labels=c("Historic, A","Future, A"))  
  scale_colour_discrete(name="", labels=c("Historic B","Future B"))  
  coord_flip() 

enter image description here

  • Related