Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine smallest elements in one category 'Other' in a pie chart R

I am trying to plot a pie chart with only 3 segments. I want the 2 largest elements and after that all the smallest elements in one category "Other" . Is there a way to do this directly from a charting package or do I need to manipulate the data set to combine all the smallest values into one. And is there a quick function to do that? Thanks for your answers.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A quick way of doing is this is by slightly formatting your data set. Since you didn’t provide an example, I borrowed one from the R Graph Gallery.

Consider a simple data frame with 5 categories (A to E):

library(tidyverse)

data <- data.frame(
  group=LETTERS[1:5],
  value=c(13,7,9,21,2)
)

We can use rank() and ifelse() to format this data into 3 groups: the two with the largest values and ‘Other’:

plotting_data <- data %>% 
  mutate(rank = rank(-value), 
         group = ifelse(rank <= 2, group, 'Other'))

And then simply use this data set for creating the pie chart:

ggplot(plotting_data, aes(x="", y=value, fill=group)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0)

pie chart with three colours

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading