2

I am working with Venn diagrams in R, ggplot2, and I would like to have the option to selectively color different parts, including the overlap between the two circles. I am limited to using ggplot2.

This is how far I have gotten. Here, I assign custom colors to the two circles, but have no control over the color of the overlap.

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

Resulting Venn diagram

I would like to be able to selectively color also the overlapping region, allowing for instance the left and right circle parts to be gray, while the overlap is colored in a solid red. Is this possible?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Jakob37
  • 57
  • 1
  • 6
  • 1
    Have a look at my question and @camille's answer how to get coordinates for overlapping polygons. https://stackoverflow.com/questions/57394946/set-opacity-of-grey-values-of-overlapping-areas-relative-to-n – tjebo Jan 02 '20 at 11:44

1 Answers1

3

You could cheat by calculating the overlap and having it as a geom_polygon.

Since the formula for your circles is (x +/- 0.5)^2 + y^2 = 1.5, you can calculate the y range since the intersections must occur on the y axis.

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

Giving you:

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87