Emman
Emman

Reputation: 4201

How to hack a grid::grob object in R to change existing text or add new?

EDIT

I don't have the underlying counts, just the end values for proportions.


Original Post

I have summary data for set intersections that I wish to visualize with R.

To visualize the data, I use the package {eulerr}. See below. However, I wish to customize the appearance of the plot, but don't know how to hack the object.

library(eulerr)

p1 <- 
  euler(c("A" = 0.205, "B" = 0.137, "A&B" = 0.0513)) |> 
  plot(quantities = TRUE,
       fills = list(fill = c("lavenderblush2", 
                             "lightblue2", 
                             "lightsalmon")))



p2 <-
  euler(c("A" = 0.205, "B" = 0.137, "A&B" = 0.0513)) |> 
  plot(quantities = FALSE,
       fills = list(fill = c("#9195F6", 
                             "#9195F6", 
                             "#9195F6")))


p1

p2

Created on 2024-04-25 with reprex v2.0.2


I know that it's a grid::grob object because:

grid::is.grob(p1)
# [1] TRUE

How could I tweak some parts of the plot, for example:

Upvotes: 0

Views: 77

Answers (1)

zx8754
zx8754

Reputation: 56229

There is no need to hack:

# show percent and counts
plot(euler(c("A" = 0.205, "B" = 0.137, "A&B" = 0.0513)), 
     quantities = list(type = c("counts", "percent")))

enter image description here


We can use gridExtra to add extra text:

library(gridExtra)
library(grid)

p1 <- plot(euler(c("A" = 0.205, "B" = 0.137, "A&B" = 0.0513)), 
           quantities = list(type = "percent"))

p1_lables <- textGrob("A or B 29%")
margin <- unit(1, "line")
grid.arrange(p1_lables, p1, ncol = 1,
             heights = unit.c(grobHeight(p1_lables) + margin,
                              grobHeight(p1) + 20 * margin))

enter image description here

Upvotes: 2

Related Questions