Home > Enterprise >  Using geom_arc_bar in ggforce
Using geom_arc_bar in ggforce

Time:10-23

I want to make a plot that looks like the one attached below which to my understanding can be achieved using the geom_arc_bar() function from the ggforce package: enter image description here

df <- data.frame(English = sample(1:100,10),
                Math = sample(1:100,10),
                History = sample(1:100,10),
                Science = sample(1:100,10),
                Group = rep(c("A","B","C","D","E"),each=2))

How would I approach this given a sample data frame, where each bar is the mean value of each group, so for this sample df, there should be 5 circles for each group (A,B,C,D,E) and each circle has the mean value of the 4 subject scores plotted in the arc? Other plotting methods are also fine (doesn't necessarily have to be by ggforce). Thanks a lot!

CodePudding user response:

First we'd need to reshape the data and precalculate the group means for each subject.

library(ggplot2)
library(ggforce)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- data.frame(English = sample(1:100,10),
                 Math = sample(1:100,10),
                 History = sample(1:100,10),
                 Science = sample(1:100,10),
                 Group = rep(c("A","B","C","D","E"),each=2))

# Reshape and calculate group means
df2 <- df %>% 
  tidyr::pivot_longer(-Group) %>%
  group_by(Group, name) %>%
  summarise(value = mean(value), .groups = "keep")

Next we'd need to define a function and some constants to help us generate the plot.

# Map discrete values to continuous
helper <- function(x) {match(x, sort(unique(x)))}

# Helper values
nsubjects <- length(unique(df2$name))
tau <- 2 * pi
arc_part <- tau / nsubjects
circle_size <- 1
circle_spacing <- 0.1
circle_offset <- 0.8 * circle_size

Lastly, we can then use ggforce::geom_arc_bar() to plot the data.

ggplot(df2)  
  # Outline circle
  geom_arc(
    data = ~ subset(.x, !duplicated(Group)),
    aes(x0 = (helper(Group) - 1) * 2 * (circle_size   circle_spacing), 
        y0 = 0, r = circle_size, start = 0, end = tau)
  )  
  # Subject quadrants
  geom_arc_bar(
    aes(x0 = (helper(Group) - 1) * 2 * (circle_size   circle_spacing),
        y0 = 0, r0 = 0,
        r = value * circle_offset / max(value),
        start = (helper(name) - 1) * arc_part,
        end   = helper(name) * arc_part,
        fill  = name)
  )  
  coord_equal()

Created on 2021-10-22 by the reprex package (v2.0.1)

There is also the vanilla ggplot2 approach:

ggplot(df2, aes(x = name, y = value, fill = name))  
  geom_col(width = 1)  
  facet_wrap(~ Group)  
  coord_polar(theta = "x")

  • Related