【问题标题】:R ggplot geom_bar: Change transparency inside bars, keeping contour/boundary the sameR ggplot geom_bar:更改条内的透明度,保持轮廓/边界相同
【发布时间】:2019-12-28 13:32:52
【问题描述】:

问题陈述

有没有办法改变ggplot2geom_bar 条形图中条形内部的透明度?基本上我想让“填充”比“颜色”更透明。

最小的工作示例

# Create fake data
df <- data.frame(language=c("Python", "Python", "R", "Julia", "R"), 
                 filetype=c("Script", "Notebook", "Notebook", "Script", "Script"), 
                 count=c(3,10,4,2,1))
# Make a barplot with ggplot
ggplot(data=df) +
 geom_bar(aes(x=filetype, y=count, fill=language), position="dodge", stat="identity")

我尝试在aes() 之外使用alpha,但它只是让一切变得透明。如果您还可以使这种透明度更改出现在图例中,则可以加分!

解决方案

我想我可能已经找到了解决方案。诀窍是在aes() 中添加color=language。我认为这有效地将填充颜色与轮廓颜色分开。这样,当我们在geom_bar 中设置alpha 的值时,我们就得到了想要的效果。这是完整的例子

# Create fake data
df <- data.frame(language=c("Python", "Python", "R", "Julia", "R"), 
                 filetype=c("Script", "Notebook", "Notebook", "Script", "Script"), 
                 count=c(3,10,4,2,1))
# Make a barplot with ggplot
ggplot(data=df) +
 geom_bar(aes(x=filetype, y=count, fill=language, color=language), 
          position="dodge", stat="identity", alpha=0.2)

【问题讨论】:

    标签: r ggplot2 plot bar-chart


    【解决方案1】:

    一个选项是添加另一层。

    ggplot(data=df, aes(x = filetype, y = count, fill = language, color = language)) +
      geom_col(
        position = position_dodge(preserve = "single"),
        alpha = 0.1
      ) +
    #  geom_col(
    #    position = position_dodge(preserve = "single"),
    #    fill = NA
    #  ) +
    NULL
    

    结果


    我又加了两分:

    1) geom_col() 而不是 geom_bar(... stat="identity")

    2) position_dodge(preserve = "single") 保持组间条形宽度一致


    编辑

    如果我们想要更少的代码,黑色边框,透明fill,并保持条在中心对齐,我们可以使用

    ggplot(data=df, aes(x = filetype, y = count, fill = language)) +
      geom_col(
        position = position_dodge2(preserve = "single"),
        alpha = 0.1,
        color = "black"
      )
    

    输出

    【讨论】:

      猜你喜欢
      • 2017-03-14
      • 2013-01-02
      • 2017-03-17
      • 2020-12-08
      • 2021-02-08
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多