Home > Enterprise >  ggplot2: Change Alpha of scale_color_viridis_c but not legend
ggplot2: Change Alpha of scale_color_viridis_c but not legend

Time:10-16

I'd like to add an alpha to my ggplot but not impact the alpha of the legend. The current solution is to add the override of : guides(color = guide_legend(override.aes = list(alpha = 1))). This works to set alpha=1 but changes the legend scale to discrete points instead of a scale.

How can I change the alpha of my color scale while retaining full visibility and the actual scale in the legend?

Example Code:

library(ggplot2)

###Generate Mock Data ###
df<- data_frame(y=seq(1:100), x=seq(1:100), z=seq(1:100))

###Plot without Alpha ###
df %>% ggplot(aes(x=x, y=y, color=z))  
  geom_point() 
  scale_color_viridis_c()

Plot without Alpha

###Plot with Alpha showing alpha on legend with continuous scale ###
df %>% ggplot(aes(x=x, y=y, color=z))  
      geom_point() 
      scale_color_viridis_c(alpha=0.01)

Plot with Alpha showing alpha on legend with continuous scale

###Plot with Alpha showing alpha=1 on legend but scale changed to discrete###

df %>% ggplot(aes(x=x, y=y, color=z))  
  geom_point() 
  scale_color_viridis_c(alpha=0.5) 
  guides(color = guide_legend(override.aes = list(alpha = 1)))

Plot with Alpha showing alpha=1 on legend but scale changed to discrete

CodePudding user response:

You can simply add your alpha to the geom_point() rather than the colour scale. Below is a reproducable example highlighting the difference between your current approach and the correct way to acchieve what you have asked, i.e., 'How can I change the alpha of my color scale while retaining full visibility and the actual scale in the legend?'

library(ggplot2)
library(vctrs)

###Generate Mock Data ###
df<- data_frame(y=seq(1:100), x=seq(1:100), z=seq(1:100))

###Plot with Alpha = 0 showing points and legend disappears###
ggplot(df,aes(x,y,color=z))  
      geom_point() 
      scale_color_viridis_c(alpha=0.00)

enter image description here

###Plot with Alpha = 0.1 showing points and legend disappears###
ggplot(df,aes(x,y,color=z))  
      geom_point() 
      scale_color_viridis_c(alpha=0.1)

enter image description here

###Plot with Alpha = 0 showing points disappear while legend remains visible###
ggplot(df,aes(x,y,color=z))  
  geom_point(alpha=0.00) 
  scale_color_viridis_c()

enter image description here

###Plot with Alpha = 0 showing points disappear while legend remains visible###
ggplot(df,aes(x,y,color=z))  
  geom_point(alpha=0.1) 
  scale_color_viridis_c()

enter image description here

  • Related