Search code examples
rggplot2pie-chartcolor-palette

Change colour of only one pie slice in R


I'm creating many pie charts with varying numbers of slices. I have created a colour palette in R and specified it's values using HEX codes.

The data frame palette has 23 colours assigned to it, and this works fine with all of my pie charts.

My question is how I would go about changing one specific slice of a pie charts to a different colour than specified in my palette. Because my pie charts have varying numbers of slices, I cannot just change one specific HEX value in my palette data frame, as this would mean the colour I'd like to change would always appear on different slices of the pie charts each time.

My code looks like so:

ggplot(Tally_5000_7499_Sorted, aes(x = "", y = n1, fill = Haplogroup)) +
  geom_bar(stat = "identity", width = 1, size = 1) +
  coord_polar("y", start = 0, direction = -1)+
  scale_fill_manual(values = palette)+
  theme_void()+
  theme(axis.line = element_blank(), axis.ticks = element_blank(), plot.title = element_text(hjust = 0.5))+
  labs(title = "Haplogroup Proportion, 5000-7499 BC")+
  ggsave("5000_7499pie2.png", dpi = 1000)

I have the colour I'd like to specify: #4f574e. I have added this colour to the data frame: Other = c("#4f574e)

I have tried to use scale_fill_manual(values = palette, "Other" = Other). This changes the correct slice but removes the colour from the rest of the pie.

I believe the solution is probably simple but I'm quite new to R and so any help would be greatly appreciated.

Thanks!


Solution

  • The only way I could set the color of a specific slice was by specifying the others by name. I'm using the iris dataset for testing since you didn't provide a sample.

    data(iris)
    library(ggplot2)
    
    ggplot(iris, aes(x = "", y = Petal.Width, fill = Species)) +
      geom_bar(stat = "identity", width = 1, size = 1) +
      coord_polar("y", start = 0, direction = -1) +
      scale_fill_manual(values=c("versicolor" = "blue", "virginica" = "purple", "setosa" = "red", "This class doesn't exist" = "black")) +
      theme_void() +
      theme(axis.line = element_blank(), axis.ticks = element_blank(), plot.title = element_text(hjust = 0.5))
    

    Notice that on scale_fill_manual you can name classes that don't exist in your dataset, so you could create a palette with all the classes you need.