【问题标题】:R ggplot2: How to draw geom_points that have a solid color and a transparent stroke and are colored depending on color?R ggplot2:如何绘制具有纯色和透明笔划并根据颜色着色的geom_points?
【发布时间】:2020-07-01 12:31:02
【问题描述】:

我想制作一个散点图,其中每个点都有一个球体。点及其球体都根据某些列值着色。

一个显示我想要的最小示例:

library(ggplot2)
library(vcd) # only needed for example dataset
ggplot(Arthritis, aes(x = ID, y = Age)) + 
    geom_point(aes(color=Sex), size=10, alpha=.3) + 
    geom_point(aes(color=Treatment), size=3)

这个“解决方案”的问题在于,使用两个geom_point 层似乎会破坏传说。我想只有一个geom_point 层并使用还添加笔划的形状也会更有意义,所以像这样:

ggplot(Arthritis, aes(x = ID, y = Age)) + 
    geom_point(aes(color=Sex, fill=Treatment), shape=21, size=5, stroke=5)

这里的传说更有意义,但是,我不知道如何使笔触透明。这很重要,因为当点重叠时您将看不到任何东西。

this 之类的答案不能解决我的问题,因为它们使用恒定颜色,因此可以使用函数 alpha。但是,我不知道是否以及如何将它与取决于数据的颜色一起使用。

TL;DR:我如何绘制具有纯色和透明笔划但不是恒定颜色的geom_points

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您在正确的轨道上认识到您可以使用函数alpha(),并意识到您不能只将alpha() 放在aes() 中。但是,您可以在任何scale_* 函数中将alpha() 作为values= 参数传递。这是一个使用mtcars的示例:

    ggplot(mtcars, aes(mpg, disp)) + 
      geom_point(
        aes(color=factor(cyl), fill=factor(carb)),
        shape=21, size=4, stroke=4) +
      scale_color_manual(values=alpha(rainbow(3), 0.2))
    

    其中一个问题是“factor(carb) 传说周围的那些大黑线不适合我。超级 ew。您可以使用 guides() 函数和使用 override.aes= 指定什么来删除它们您想在此处显示以及替换它的内容。在这种情况下,您可以设置 color=NA 以覆盖继承的美学为透明(仅保留 fill= 部分)。

    ggplot(mtcars, aes(mpg, disp)) + 
      geom_point(
        aes(color=factor(cyl), fill=factor(carb)),
        shape=21, size=4, stroke=4) +
      scale_color_manual(values=alpha(rainbow(3), 0.2)) +
      guides(fill=guide_legend(override.aes = list(color=NA))) +
      labs(color="cyl", fill="carb")
    

    顺便说一句,没有简单的方法可以将笔划“放在”geom_point 的填充部分“后面”。您可能可以为此编写自己的自定义 stat/geom,但 geom_point 总是先填充,然后是描边。

    【讨论】:

    • 非常好的解决方案。
    【解决方案2】:

    解决此问题的一种简单方法是使较大的透明圆圈根本不是点,而是实心圆圈。这样您就可以使用fill 美学来标记它们。这使用来自ggforcegeom_circle

    library(ggplot2)
    library(vcd)
    library(ggforce)
    
    ggplot(Arthritis) + 
      geom_circle(aes(x0 = ID, y0 = Age, r = 2, fill = Sex), alpha = .3, colour = NA) +
      geom_point(aes(x = ID, y = Age, color = Treatment), size = 3) + 
      coord_equal() + 
      scale_color_discrete(h = c(350, 190))
    

    reprex package (v0.3.0) 于 2020-07-01 创建

    【讨论】:

      【解决方案3】:

      或者制作第二个色标!

      我也在使用 see::geom_point2,因为它不会在透明点周围制作这个小边框。

      library(ggplot2)
      library(vcd) 
      library(ggnewscale)
      library(see)
      
      ggplot(Arthritis, aes(x = ID, y = Age)) + 
        geom_point2(aes(color=Sex), size=10, alpha=.3) + 
        new_scale_color()+
        geom_point(aes(color=Treatment), size=3)
      

      reprex package (v0.3.0) 于 2020-07-01 创建

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        • 2019-09-09
        • 2015-11-08
        • 2014-09-04
        • 1970-01-01
        相关资源
        最近更新 更多