简体   繁体   中英

ggplot2: Change Alpha of scale_color_viridis_c but not legend

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()

没有 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)

用 Alpha 绘图,在具有连续比例的图例上显示 Alpha

###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)))

用 Alpha 绘图,图例上显示 alpha=1,但比例更改为离散

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, ie, '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)

在此处输入图片说明

###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)

在此处输入图片说明

###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()

在此处输入图片说明

###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()

在此处输入图片说明

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