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

时间:2020-07-01 12:31:02

标签: r ggplot2

我想绘制一个散点图,其中每个点都得到一个球体。点和其球体均根据某些列值着色。

显示我想要的最小示例:

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)

enter image description here

此“解决方案”的问题在于,使用两个geom_point层似乎会使图例混乱。我猜想,只有一层geom_point并使用还会增加笔触的形状会更有意义,所以像这样:

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

enter image description here 图例在这里更有意义,但是,我无法弄清楚如何使笔触透明。这很重要,因为当点重叠时,您什么也看不到。

this这样的答案不能解决我的问题,因为它们使用恒定的颜色,因此可以使用函数alpha。但是,我无法弄清楚是否以及如何将其用于取决于数据的颜色。

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

3 个答案:

答案 0 :(得分:6)

您在正确的道路上认识到可以使用函数alpha(),并且已经意识到不能仅将alpha()放在aes()中。但是,您可以在任何alpha()函数中将values=作为scale_*参数传递。这是使用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))

enter image description here

一个问题是,“ factor(carb)图例周围的大黑线不太适合我。超级棒。您可以使用guides()函数和{{ 1}}来指定要显示的内容和替换的内容,在这种情况下,您可以将override.aes=设置为覆盖继承的美感,使其透明(仅保留color=NA部分)。

fill=

enter image description here

顺便说一句,没有简单的方法将笔划放在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总是先填充然后再描边绘制。

答案 1 :(得分:4)

解决这个问题的一种简单方法是使其较大的透明圆根本不是点,而是实心圆。这样,您可以使用fill美学来标记它们。这使用了geom_circle中的ggforce

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创建

答案 2 :(得分:1)

或设置第二个色标!

我还使用了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创建