Search code examples
rggplot2donut-chart

ggplot2 donut chart with gradient of colors


I want to build a standard function to plot a donut chart in R. The following question helps me a lot, but I can't colour the plot with a gradient of n colors ranging from color 1 and color 2.

My code:

donut_chart <- function(data,variable1,variable2,col1="red",col2="yellow")
{
# Add addition columns to data, needed for donut plot.
data[,"fraction"] = data[,"variable2"]/ sum(data[,"variable2"])
data[,"ymax"] = cumsum(data[,"fraction"])
data[,"ymin"] = c(0, head(data[,"ymax"], n = -1))

# Palette

colfunc <- colorRampPalette(c(col1,col2))   

# Donut plot
ggplot(data, aes(fill = variable1, ymax = ymax, ymin = ymin, xmax = 4, xmin = 3)) +
     geom_rect(colour = "white", show_guide = FALSE) +
    coord_polar(theta = "y") + xlim(c(0, 4)) +
    scale_fill_manual(values=c(colfunc(levels(data[,"variable1"])))+ 
    theme_bw() + 
    theme(panel.grid=element_blank()) + 
    theme(axis.text=element_blank()) + 
    theme(axis.ticks=element_blank()) + 
    geom_text(aes(x = 3.5, y = ((ymin+ymax)/2), label = type),colour="white",size=6,fontface="bold") + 
    xlab("") + 
    ylab("")
    }

The data.frame:

ad = data.frame(
  type = c("Poster", "Billboard", "Bus", "Digital"),
  n = c(529, 356, 59, 81)
)

Output code:

donut_chart(ad,"type","n")

The output plot is colored only with red color.


Solution

  • Be careful when creating function. Sometimes you wrote variable as character and sometimes it was the other way around. Also be wary of missing parentheses. This seems to work:

    donut_chart <- function(data,variable1,variable2,col1="red",col2="yellow")
    {
      # Add addition columns to data, needed for donut plot.
      data[,"fraction"] = data[,variable2]/ sum(data[,variable2])
      data[,"ymax"] = cumsum(data[,"fraction"])
      data[,"ymin"] = c(0, head(data[,"ymax"], n = -1))
    
      # Palette
    
      colfunc <- colorRampPalette(c(col1,col2))   
    
      # Donut plot
      ggplot(data, aes_string(fill = variable1, ymax = "ymax", ymin = "ymin", xmax = 4, xmin = 3)) +
        geom_rect(colour = "white", show.legend  = FALSE) +
        coord_polar(theta = "y") + xlim(c(0, 4)) +
        scale_fill_manual(values=c(colfunc(length(data[,variable1]))))+ 
                            theme_bw() + 
                            theme(panel.grid=element_blank()) + 
                            theme(axis.text=element_blank()) + 
                            theme(axis.ticks=element_blank()) + 
                            geom_text(aes(x = 3.5, y = ((ymin+ymax)/2), label = type),colour="black",size=6,fontface="bold") + 
                            xlab("") + 
                            ylab("")
    }
    donut_chart(ad,"type","n")
    

    Which gives (I changed the colour of the text because white on white was hard to read): enter image description here