我試圖在兩個因素(應變和性別)之間繪制一個圖,并使用 alpha 值來傳達性別。這是我的代碼和結果圖:
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)反映為灰度/黑色,因為我認為這很直觀。
我試過改變 scale_alpha_discrete,但無法弄清楚如何為圖例發送單一顏色。我也試過玩 'guides()' ,但運氣不佳。我懷疑有一個簡單的解決方案,但我看不到它。
uj5u.com熱心網友回復:
實作所需結果的一種選擇是alpha通過override.aes引數設定圖例的填充顏色guide_legend。
使用 mtcars作為示例資料:
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.

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315859.html
