Search code examples
rdonut-chart

How do I get a Donut Chart in R?


I try to draw a Donut Chart with a tutorial code but I get an error I cannot explain.

enter image description here

library(ggplot2)
library(dplyr)

Calculate and cumulate percentages

df$fraction = df$freq / sum(df$freq)
df$ymax = cumsum(df$fraction)
df$ymin = c(0, head(df$ymax, n=-1))

Draw chart

ggplot(df, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) +
  geom_rect() +
  coord_polar(theta="y") + 
  xlim(c(2, 4)) 

I get this error:

Error in geom_rect(): ! Problem while computing aesthetics. ℹ Error occurred in the 1st layer. Caused by error in FUN(): ! object 'category' not found Run rlang::last_error() to see where the error occurred.


Solution

  • You need to change fill=category to fill=word, then it works:

    df <- data.frame (word  = c("dolor", "amet", "diam", "ipsum", "lorem", "sed", "sit", "accusam", "aliquyam", "clita"),freq = c(48,24,24,24,24,24,24,12,12,12))
    
    library(ggplot2)
    library(dplyr)
    
    df$fraction = df$freq / sum(df$freq)
    df$ymax = cumsum(df$fraction)
    df$ymin = c(0, head(df$ymax, n=-1))
    
    ggplot(df, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, 
    fill=word)) +
    geom_rect() +
    coord_polar(theta="y") + 
    xlim(c(2, 4))