Search code examples
rggplot2ggplotly

Nested donut chart for comparison


I am trying to make two donut plots to compare some metrics. The data frame is as below,

new_sum    var                 `1`   `2`
    <dbl> <chr>               <dbl> <dbl>
1    98.7 cnt_alerts           45.1  NA  
2    98.7 cnt_incidents_total  15.6  NA  
3    98.7 sum_of_events       100    NA  
4   100   cnt_alerts           NA    44.4
5   100   cnt_incidents_total  NA    16.2
6   100   sum_of_events        NA   100

So the two plots should represent the 1 and 2 columns, but the row sum_of_events should be taken from new_sum column. So in the end the two plots will look as follows (Trying to replicate with paint)

enter image description here

DATA

structure(list(new_sum = c(98.7093505166464, 98.7093505166464, 
98.7093505166464, 100, 100, 100), var = c("cnt_alerts", "cnt_incidents_total", 
"sum_of_events", "cnt_alerts", "cnt_incidents_total", "sum_of_events"
), `1` = c(45.0519047096481, 15.6423424701131, 100, NA, NA, NA
), `2` = c(NA, NA, NA, 44.4483592005942, 16.201786624667, 100
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-6L))

Solution

  • Something like this?

    library(tidyverse)
    df1 %>% 
      mutate(
        id = rep(1:2, each = 3),
        value = coalesce(`1`, `2`),
        value = ifelse(var == "sum_of_events", new_sum, value)
      ) %>% 
      ggplot(aes(var)) + 
      geom_col(aes(y = 100), position = 'identity', fill = 'white', col = 1, width = 0.5) +
      geom_col(aes(y = value), position = 'identity', fill = 'grey60', col = 1, width = 0.5) +
      facet_grid(~id) +
      coord_polar(theta = 'y') +
      theme_minimal()
    

    enter image description here