D.Parker
D.Parker

Reputation: 171

Creating multiple pie charts with a single dataset

I have a larger version of the following data table, with about 40 different species:

library(ggplot2)

dat <- read.table(text = "    Species Count 
Species_1   1
Species_1   2  
Species_1   2  
Species_2   1  
Species_2   3  
Species_2   4  
Species_2   4  
Species_2   3  
Species_2   4  
Species_2   2 
Species_2   1  
Species_2   1 ",sep = "",header = TRUE)

I would like to make pie charts for each species, that display the proportion of counts for each species. For example, in this case, for Species_1, I would have a pie chart that was 1/3 colored for "1", and 2/3 colored for "2". I want these types of pie charts for all the species. I almost did this with the following code:

dat$Count <- as.character(dat$Count)

pie <- ggplot(dat, aes(x=1, y=Count, fill=Count)) +
  geom_bar(stat="identity") +
  coord_polar(theta='y') + facet_wrap(~Species) + theme_void()

pie

But when I do more than one species, it makes pie charts based on the species with the largest number of observations. So in this case, Species_1 is not completely filled. But I want a proportion of counts for each species, so that all the pie charts are completely filled. Is there an easy way to do this?

Upvotes: 0

Views: 1053

Answers (1)

s__
s__

Reputation: 9485

maybe this can help:

library(ggplot2)

dat <- read.table(text = "    Species Count 
Species_1   1
Species_1   2  
Species_1   2  
Species_2   1  
Species_2   3  
Species_2   4  
Species_2   4  
Species_2   3  
Species_2   4  
Species_2   2 
Species_2   1  
Species_2   1 ",sep = "",header = TRUE)

dat$Count <- as.factor(Count)
dat$Count1 <- 1

pie <- ggplot(dat, aes(x=1, y=Count1, fill=as.factor(Count))) +coord_polar(theta='y')+
  geom_bar(position= 'fill',stat="identity") + facet_grid(~Species) + theme_void()

pie

enter image description here

Upvotes: 2

Related Questions