简体   繁体   中英

Different alpha values by facet with facet_wrap in ggplot

I have two graphs from a single long data frame that is faceted based on one of the columns. This produces one facet plot with way way more observations than the other. I want to set a low alpha value for the facet with far more observations but preserve the default alpha for the facet with fewer observations.

Here is a reproduction of my code.

df <- data.frame(spons=sample(c(1:100),10000, replace=T), variable='score', value=runif(10000, -1,1), time=rep(1:10, 1000), DataSub=sample(c('original', 'matched'),10000,replace=T,  prob=c(0.01, 0.99)))
p <- ggplot(df, aes(x=factor(time), y=factor(spons)))
p+geom_point()+facet_grid(DataSub~., ncol=2)

What I want it to look like is the more dense of the plots to have alpha= 0.01 or something like that but leave the more sparse of the plots alone.

Thanks.

You can do this by using the same variable that you used to facet as an alpha aesthetic, then setting the values manually, as follows

p+geom_point(aes(alpha=DataSub))+
   facet_grid(DataSub~.)+scale_alpha_manual(values=c(0.01,1))

This helps, but on my screen at least it's hard to make out much density variation in the upper panel ( values=c(0.02,1) seems a little better: additionally using theme_bw()+ theme(panel.grid.minor=element_blank(),panel.grid.major=element_blank()) helps a bit more by clearing out the background, but you may not want to go that far)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM