0

I want to accentuate the area in the faceted density plots above the measure threshold of 2 (e.g., red shading for x=>2). This solution works well for a single facet factor, but I have two factors. How do I specify the levels for the two factors when using ggplot_build? Or do I need to use a different approach?

Here's a bit of the dataframe (the dataframe is 750 rows):

    mode.f task.f      mgds
1        1      A 1.1413636
2        1      A 0.9105000
3        2      A 1.0320000
4        2      A 1.1811429
14       1      C 1.4646000
15       1      C 1.7505000
16       2      C 1.3968000
17       1      D 1.0668333
18       1      D 1.0084000
19       1      D 1.1622500
20       2      D 1.3452500
21       2      D 1.0132000
22       3      C 0.6960000
23       3      C 0.9180000
24       3      D 1.0128000
25       3      D 0.6670000
26       2      E 2.9190000
27       2      E 1.3755000
28       2      E 1.4080000
29       1      E 1.3878000
30       1      E 1.4816667

Here's the code that works for a single facet factor:

mp <- ggplot(df,aes(x=mgds))+
  geom_density(color=NA,fill="gray30",alpha=.4)+
  facet_wrap(~mode.f)+
  theme_bw()+
  theme(strip.background = 
        element_rect(fill="gray95",color="gray60"),
        strip.text = element_text(colour="black",size=10),
        panel.border = element_rect(color="gray60"))+
  labs(x="MGD (s)",y="Density")

to_fill <- data_frame(
  x = ggplot_build(mp)$data[[1]]$x,
  y = ggplot_build(mp)$data[[1]]$y,
  mode.f = factor(ggplot_build(mp)$data[[1]]$PANEL, levels = 
  c(1,2,3), labels = c("1","2","3")))

mp + geom_area(data = to_fill[to_fill$x >= 2, ], 
               aes(x=x, y=y), fill = "red")

Here's the code for the facet_grid plots that I want to have the area beyond the x=2 threshold be a different color 2

ggplot(df,aes(x=mgds))+
  geom_density(color=NA,fill="gray30",alpha=.4)+
  facet_grid(~mode.f~task.f)+
  theme_bw()+
  theme(strip.background = element_rect(fill="gray95",color="gray60"),
        strip.text = element_text(colour="black",size=10),
        panel.border = element_rect(color="gray60"))+
  geom_vline(xintercept=2,linetype="longdash",color="gray50")+
  labs(x="Measure",y="Density")

0 Answers0