使用单个数据集创建多个饼图

Creating multiple pie charts with a single dataset

我有以下数据的放大版本table,大约有 40 个不同的物种:

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)

我想为每个物种制作饼图,显示每个物种的计数比例。例如,在这种情况下,对于 Species_1,我会有一个饼图,其中 1/3 颜色表示“1”,2/3 颜色表示“2”。我想要所有物种的这些类型的饼图。我几乎用以下代码做到了这一点:

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

但是当我做一个以上的物种时,它会根据观测值最多的物种制作饼图。所以在这种情况下,Species_1 并没有完全填满。但我想要每个物种的计数比例,以便所有饼图都被填满。是否有捷径可寻?

也许这可以帮助:

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