johnny2554
johnny2554

Reputation: 43

How do I group categories together in a pie chart based on a count variable?

I'm in the process of making a pie chart in ggplot2. I have a dataset situated like so:

category<- c("a", "b", "c", "d", "e")
count<- c(1,1,4,5,1)
df<- cbind(category, count)

Creating an output like: |category|count| |--------|-----| |a |1 | |b |1 | |c |4 | |d |5 | |e |1 |

The code I currently have for my Pie Chart:

ggplot(Distincts, aes(y=count, x="", fill= category )) + geom_bar(stat="identity") + 
  coord_polar("y", start = 0)

I want to create a pie chart that has counts for every corresponding category. However, I would like to group all categories with a count of less than a number (i.e. <2) into one category named "unique"- is there any input as to how to do this? I want the pie chart to look something like:

Pie Chart Example

Thanks again!

Upvotes: 0

Views: 1099

Answers (1)

stefan
stefan

Reputation: 124268

Maybe you are looking for forcats::fct_lump_min which allows you to lump categories into a "Other" category depending on the frequency. After lumping you could make use of count to compute the aggregated count for the lumped category:

category<- c("a", "b", "c", "d", "e")
count<- c(1,1,4,5,1)
df<- data.frame(category, count)

library(ggplot2)
library(forcats)
library(dplyr)

df <- df %>% 
  mutate(category = forcats::fct_lump_min(category, 2, count, other_level = "Unique")) %>% 
  count(category, wt = count, name = "count")

ggplot(df, aes(y=count, x="", fill= category)) + 
  geom_bar(stat="identity") + 
  coord_polar("y", start = 0)

Upvotes: 1

Related Questions