首页 > 解决方案 > 使用单个数据集创建多个饼图

问题描述

我有以下数据表的更大版本,大约有 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”的颜色为 1/3,“2”的颜色为 2/3。我想要所有物种的这些类型的饼图。我几乎用以下代码做到了这一点:

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 没有被完全填充。但我想要每个物种的计数比例,这样所有的饼图都被完全填满。是否有捷径可寻?

标签: rggplot2pie-chart

解决方案


也许这可以帮助:

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

在此处输入图像描述


推荐阅读