Home > Enterprise >  R ggplot2 scale alpha discrete to display in legend
R ggplot2 scale alpha discrete to display in legend

Time:10-10

I'm trying to make a plot across two factors (strain and sex) and use the alpha value to communicate sex. Here is my code and the resulting plot:

ggplot(subset(df.zfish.data.overall.long, day=='day_01' & measure=='distance.from.bottom'), aes(x=Fish.name, y=value*100))  
  geom_boxplot(aes(alpha=Sex, fill=Fish.name), outlier.shape=NA)  
  scale_alpha_discrete(range=c(0.3,0.9))  
  scale_fill_brewer(palette='Set1')  
  coord_cartesian(ylim=c(0,10))  
  ylab('Distance From Bottom (cm)')  
  xlab('Strain')  
  scale_x_discrete(breaks = c('WT(AB)', 'WT(TL)', 'WT(TU)', 'WT(WIK)'), labels=c('AB', 'TL', 'TU', 'WIK'))  
  guides(color=guide_legend('Fish.name'), fill=FALSE)  
  theme_classic(base_size=10)

enter image description here

I'd like for the legend to reflect the alpha value in the plot (i.e. alpha value F = 0.3, alpha value M=0.9) as greyscale/black as I think that will be intuitive.

I've tried altering the scale_alpha_discrete, but cannot figure out how to send it a single color for the legend. I've also tried playing with 'guides()' without much luck. I suspect there's a simple solution, but I cannot see it.

CodePudding user response:

One option to achieve your desired result would be to set the fill color for the alpha legend via the override.aes argument of guide_legend.

Making use of mtcars as example data:

library(ggplot2)

ggplot(mtcars, aes(x = cyl, y = mpg))  
  geom_boxplot(aes(fill = factor(cyl), alpha = factor(am)))  
  scale_alpha_discrete(range = c(0.3, 0.9), guide = guide_legend(override.aes = list(fill = "black")))  
  scale_fill_brewer(palette='Set1')  
  theme_classic(base_size=10)  
  guides(fill = "none")
#> Warning: Using alpha for a discrete variable is not advised.

  • Related