繁体   English   中英

R ggplot2:如何绘制具有纯色和透明笔划并根据颜色着色的geom_points?

[英]R ggplot2: How to draw geom_points that have a solid color and a transparent stroke and are colored depending on color?

我想做一个散点图 plot 每个点都有一个球体。 点及其球体都根据某些列值着色。

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

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)

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

这样的答案不能解决我的问题,因为它们使用恒定的颜色,因此可以使用 function alpha 但是,我不知道是否以及如何将它与依赖于数据的 colors 一起使用。

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

您在正确的轨道上认识到您可以使用 function 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() function并使用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总是先用填充绘制,然后是描边。

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

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))

代表 package (v0.3.0) 于 2020 年 7 月 1 日创建

或者制作第二个色标!

library(ggplot2)
library(vcd) 
#> Loading required package: grid
library(ggnewscale)

ggplot(Arthritis, aes(x = ID, y = Age)) + 
  ## removing stroke so it does not have this awkward border around it
  geom_point(aes(color=Sex), size=10, alpha=.3, stroke = 0) +
  new_scale_color()+
  geom_point(aes(color=Treatment), size=3) 

代表 package (v2.0.1) 于 2022 年 6 月 15 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM