'R Pie Donut chart with facet functionality

The following code works fine and produces the required graph as given below:

library(tidyverse)
library(ggiraphExtra)

library(moonBook)

ggPieDonut(data = acs, mapping = aes(pies = Dx, donuts = smoking), interactive = TRUE)

enter image description here

Wondering how to construct Pie Donut chart with facet functionality. My attempt is below:

ggPieDonut(data = acs, mapping = aes(pies = Dx, donuts = smoking), interactive = TRUE) +
  facet_wrap(facets = vars(sex))
NULL


Solution 1:[1]

It seems @jpiversen and I had the same idea about this, so I initially didn’t post my answer after seeing theirs. However, by request of the OP, and in case it proves useful in some way, here’s my take on this:


I think the short answer is: you can’t.

There’s no option for facetting in the function call, and the resulting ggplot2 object has had it’s data modified enough to not have access to the original columns anymore, making ggplot facetting afterwards impossible.

However, you can get in the vicinity of facetting by constructing the plots separately for each level of the variable you wanted to facet by, and then assembling the plots together.

Here’s how I’d approach that:

library(tidyverse)
library(ggiraphExtra)

library(moonBook)

make_plot <- function(data) {
  ggPieDonut(data = data, mapping = aes(pies = Dx, donuts = smoking))
}

plots <- by(acs, acs$sex, make_plot)
combined_plots <- patchwork::wrap_plots(plots) +
  patchwork::plot_annotation(tag_levels = list(names(plots)))

combined_plots

I don’t know how to do the combination step if you specify interactive = TRUE, but as a workaround some approximation of interactivity could be also reached with a simple girafe() call on the combined plots:

ggiraph::girafe(code = print(combined_plots))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikko Marttila