Search code examples
rcolorsggplot2donut-chart

Trying to change the coloring of a ggplot graph in R


I am trying to replicate the donut graph in the picture below.

Attempting to replicate

I have completed everything but the actual coloring, and am confused as to what I am doing incorrectly in the scale_colour_manual portion of ggplot.

Here's the code that I am using for ggplot:

    ggplot(base_ind_zones) + 
    geom_rect(aes(fill = base_zones, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
    geom_rect(aes(fill = ind, ymax=ymax, ymin=ymin, xmax=3, xmin=2)) +  
    xlim(c(0, 4)) + 
    theme(aspect.ratio=1) +
    coord_polar(theta = "y", start = ((2*3.14)/3)) +
    theme(panel.grid=element_blank()) +
    theme(axis.text=element_blank()) +
    theme(axis.ticks=element_blank()) +
    scale_colour_manual(breaks = c("A", "B", "C", "D"),
    values = c(adjustcolor("blue", alpha.f = 0), "firebrick4", "grey99", "skyblue1"))

and a sample data set:

    base_ind_zones <- base_ind_zones = data.frame(category=c("A", "B", "C", "D"),
    base_zones=c(33, 44, 12, 11),
    ind=c(33, 44, 2, 21))

    #Needed to determine the ymin and ymax for ggplot
    base_ind_zones$fraction = base_ind_zones$ind / sum(base_ind_zones$ind)
    base_ind_zones$ymax = cumsum(base_ind_zones$fraction)
    base_ind_zones$ymin = c(0, head(base_ind_zones$ymax, n = -1))

Current output

Before adding scale_colour_manual, I get the above donut graph. After adding the scale_colour_manual, there was no change in coloring. What changes do I need to make to scale_colou_manual to change the coloring? If I am not on the right track, I would really appreciate any sort of guidance. Thanks in advance!


Solution

  • base_ind_zones <- data.frame(category=c("A", "B", "C", "D"),
                                              base_zones=as.character(c(33, 44, 12, 11)),
                                              ind=as.character(c(33, 45, 2, 21)),
                             stringsAsFactors = FALSE)
    
    #Needed to determine the ymin and ymax for ggplot
    base_ind_zones$fraction = as.numeric(base_ind_zones$ind) /
      sum(as.numeric(base_ind_zones$ind))
    base_ind_zones$ymax = cumsum(base_ind_zones$fraction)
    base_ind_zones$ymin = c(0, head(base_ind_zones$ymax, n = -1))
    
    ggplot(base_ind_zones) + 
      geom_rect(aes(fill = base_zones, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
      geom_rect(aes(fill = ind, ymax=ymax, ymin=ymin, xmax=3, xmin=2)) +  
      xlim(c(0, 4)) + 
      theme(aspect.ratio=1) +
      coord_polar(theta = "y", start = ((2*3.14)/3)) +
      theme(panel.grid=element_blank()) +
      theme(axis.text=element_blank()) +
      theme(axis.ticks=element_blank()) +
      scale_fill_manual(breaks = c("A", "B", "C", "D"),
                  values = c("33"="white", "44"="firebrick4", "12"="white", 
                             "11"="skyblue1", "2"="black", "21"="white", "45"="black"))
    

    enter image description here