【问题标题】:R ggplot2 scale alpha discrete to display in legendR ggplot2缩放alpha离散以显示在图例中
【发布时间】:2021-11-29 03:37:39
【问题描述】:

我正在尝试跨两个因素(应变和性别)绘制一个图,并使用 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()'但运气不佳。我怀疑有一个简单的解决方案,但我看不到它。

【问题讨论】:

    标签: r ggplot2 alpha


    【解决方案1】:

    实现所需结果的一种方法是通过guide_legendoverride.aes 参数为alpha 图例设置填充颜色。

    使用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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 2015-05-26
      • 2013-12-16
      • 2020-08-13
      相关资源
      最近更新 更多