首页 > 解决方案 > 使用 ggplot2 自定义维恩重叠区域的颜色

问题描述

我正在使用 R,ggplot2 中的维恩图,我希望可以选择为不同的部分着色,包括两个圆圈之间的重叠。我仅限于使用 ggplot2。

这就是我已经走了多远。在这里,我为两个圆圈分配了自定义颜色,但无法控制重叠的颜色。

library(ggplot2)

df.venn <- data.frame(x = c(-0.5, 0.5),
                      y = c(0, 0),
                      labels = c("A", "B"),
                      stringsAsFactors = FALSE)

ggplot2::ggplot(data=df.venn) +
    ggforce::geom_circle(
        ggplot2::aes_string(x0 = "x", y0 = "y", r = 1.5, fill = "labels"), 
        alpha = 0.3, 
        size = 0.5, 
        colour = 'darkgray'
    ) +
    ggplot2::coord_fixed() +
    ggplot2::theme_void() +
    ggplot2::scale_fill_manual(values = c("red", "blue"))

生成的维恩图

我希望能够选择性地为重叠区域着色,例如允许左右圆形部分为灰色,而重叠部分为纯红色。这可能吗?

我感谢任何输入!

标签: rggplot2

解决方案


您可以通过计算重叠并将其作为 geom_polygon 来作弊。

由于您的圆的公式是 (x +/- 0.5)^2 + y^2 = 1.5,因此您可以计算 y 范围,因为交点必须发生在 y 轴上。

library(ggplot2)

df.venn <- data.frame(x = c(-0.5, 0.5),
                      y = c(0, 0),
                      labels = c("A", "B"),
                      stringsAsFactors = FALSE)

yvals <- seq(-sqrt(2), sqrt(2), 0.01)
xvals <- sqrt(2.25 - yvals^2) - 0.5
yvals <- c(yvals, rev(yvals))
xvals <- c(xvals, -xvals)
combo <- data.frame(x = xvals, y = yvals)



ggplot2::ggplot(data = df.venn) +
    ggforce::geom_circle(
        ggplot2::aes_string(x0 = "x", y0 = "y", r = 1.5, fill = "labels"),
        alpha = 0.3,
        size = 1,
        colour = 'darkgray'
    ) +
    ggplot2::geom_polygon(data = combo, aes(x = x, y = y), fill = "red") +
    ggplot2::coord_fixed() +
    ggplot2::theme_void() +
    ggplot2::scale_fill_manual(values = c("gray50", "gray50"))

给你:

在此处输入图像描述


推荐阅读