【问题标题】:Change opacity on part of a geom_bar object更改部分 geom_bar 对象的不透明度
【发布时间】:2017-03-14 01:13:38
【问题描述】:

我正在尝试更改 ggplot 条形图的不透明度。考虑以下示例:

df <- data.frame(period = rep(c("current", "past"), 3), 
                 type = c("so_far", "so_far", "source_x", "source_x", "source_y", "source_y"), 
                 income = c(12, 10, 7, 9, 4, 7))
ggplot(df, aes(x = period, y = income, fill = type)) + geom_bar(stat = "identity")

这给出了以下情节:

实际上,尽管当前时期的 source_x 和 source_y 是估计值,而在过去它们是真实值。所以我想改变左侧栏上蓝色和绿色部分的不透明度。 这可以做到吗?怎么样?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    虚线边框在这里可能会更好地突出显示包含估计值的条形部分。在下面的代码中,我使用线型和 alpha 美学来标记估计的两个条形部分。我还颠倒了图例,以便颜色顺序与堆叠条的颜色顺序相对应。

    library(ggplot2)
    
    ggplot(df, aes(x = period, y = income, fill = type, 
                   linetype=ifelse(grepl("current", period) & grepl("source", type), "B", "A"),
                   alpha=ifelse(grepl("current", period) & grepl("source", type), 0, 1))) + 
      geom_bar(stat = "identity", lwd=0.5, colour="grey40") +
      scale_alpha(range=c(0.5,1)) + 
      theme_bw() +
      guides(alpha=FALSE, linetype=FALSE,
             fill=guide_legend(reverse=TRUE))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-12
      • 2011-11-30
      • 1970-01-01
      • 2011-01-20
      • 2013-03-23
      • 2013-07-28
      • 2013-03-04
      • 2012-01-20
      相关资源
      最近更新 更多