R ggplot2 缩放 alpha 离散以显示在图例中 [英] R ggplot2 scale alpha discrete to display in legend
问题描述
我正在尝试绘制跨两个因素(应变和性别)的图,并使用 alpha 值来传达性别.这是我的代码和结果图:
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)
我希望图例将图中的 alpha 值(即 alpha 值 F = 0.3,alpha 值 M=0.9)反映为灰度/黑色,因为我认为这会很直观.
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.
我尝试更改 scale_alpha_discrete,但无法弄清楚如何为图例发送单一颜色.我也试过玩 'guides()' ,但运气不佳.我怀疑有一个简单的解决方案,但我看不到.
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.
推荐答案
实现所需结果的一个选项是通过 override.aes 设置
alpha
图例的填充颜色guide_legend
的参数.
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
.
使用 mtcars
作为示例数据:
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.
这篇关于R ggplot2 缩放 alpha 离散以显示在图例中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!