Search code examples
rggplot2polar-coordinates

How to plot ggplot2 polar with discret/continuous values instead of counting?


with the code below

dft <- data.frame(f1=c('A', 'B', 'C', 'A', 'A', 'D'), 
                  f2=c("F1", "F1", "F2", 'F2', 'F3', 'F1'))
d <- ggplot(dft, aes(x =f1, fill=f2))
d <- d + geom_bar(width = 1, position = "fill")
d + coord_polar("x") 

I get this chart

enter image description here

The number of sectors is determined by f1, and the records counts produce the proportion of f2 on each f1 accordingly.

But I want to have the sectors filled based on a continuous/discrete aggregated value.

Instead of

dft <- data.frame(f1=c('A', 'B', 'C', 'A', 'A', 'D'), 
                  f2=c("F1", "F1", "F2", 'F2', 'F3', 'F1'))

I'd have

dft2 <- data.frame(f1=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'), 
                   f2=c("F1", "F2", "F3", "F1", "F2", "F3", "F1", "F2", "F3"), 
                   value=c(5,10,15, 2,30,30, 10, 10,20))

is that possible?

Thanks


Solution

  • You can try this:

    dft2 <- data.frame(f1=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'), 
                       f2=c("F1", "F2", "F3", "F1", "F2", "F3", "F1", "F2", "F3"), 
                       value=c(5,10,15, 2,30,30, 10, 10,20))
    
    d2 <- ggplot(dft2, aes(x = f1, y = f2, fill = value)) + 
      geom_col(width = 1) +
      scale_fill_gradient2(low = 'dodgerblue1', high = 'dodgerblue4') +
      coord_polar("x") +
      theme_minimal() +
      theme(axis.text.y = element_blank())
    

    It uses geom_col and the y aesthetic, mapping it to f2, while filling by the value dimension. Colors are just for fun. Change or remove as you wish.

    enter image description here

    If you want each f2 area relative to its value change the y aesthetic to value:

    d2 <- ggplot(dft2, aes(x = f1, y = value, fill = value)) + 
      geom_col(width = 1, position = 'fill', color = 'black', size = .5) +
      scale_fill_gradient(low = 'dodgerblue1', high = 'dodgerblue4') +
      coord_polar("x") +
      theme_minimal() +
      theme(axis.text.y = element_blank())
    

    enter image description here