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 :
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)
