首页 > 解决方案 > For 循环为数据框中的所有唯一值创建直方图

问题描述

我有 18 个不同的物种,它们的大小等级和每个大小等级的观察计数。我正在尝试创建一个 for 循环,该循环将为每个物种创建一个单独的直方图(不是方面,因为有太多物种)。For 循环是我在 R 中最薄弱的领域,我经常做更多的代码来避免它们,但有 18 个物种不再是一种选择。

这是我的格式化数据示例:

Species    Size.Class   TotalCount
P. porphyreus   35  1
P. porphyreus   20  5
P. porphyreus   25  5
P. insularis    35  2
P. insularis    5   10
P. insularis    10  10
P. insularis    30  12
P. insularis    25  35
P. insularis    15  36
P. insularis    20  36
P. cyclostomus  30  2
P. cyclostomus  35  2
P. cyclostomus  25  4
P. cyclostomus  15  7
P. cyclostomus  20  8

当我为一个物种创建直方图时,我得到了预期的结果:

ggplot(subset(Spcount,Species %in% c("P. porphyreus")),aes(x=Size.Class))+
  geom_histogram(binwidth=5)+
  ggtitle("P. porphyreus Histogram")+
  labs(y= "Total Count", x = "Size Class")

但是当我尝试使用这个 for 循环自动化它时:

FOR (i in Spcount$Species) {
  ggplot(subset(Spcount,Species %in% c("i")),aes(x=Size.Class))+
    geom_histogram(binwidth=5)+
    ggtitle("i Histogram")+
    labs(y= "Total Count", x = "Size Class") 
}

我得到一个标题为“i Histogram”的图表,但它是空白的,没有错误或警告。

标签: rfor-loopggplot2graph

解决方案


您应该对 Species 的唯一值进行子集化,通过for (i in unique(Spcount$Species))

首先,我制作您的示例数据:

Spcount <- data.frame(
  Species = c(
    "P. porphyreus", "P. porphyreus", "P. porphyreus",
    "P. insularis", "P. insularis", "P. insularis", "P. insularis",
    "P. insularis", "P. insularis", "P. insularis", "P. cyclostomus", 
    "P. cyclostomus", "P. cyclostomus", "P. cyclostomus", "P. cyclostomus"
    ),
  Size.Class = c(
    35, 20, 25, 35, 5, 10, 30, 25, 15, 20, 30, 35, 25, 15, 20
  ),
  TotalCount = c(
    1, 5, 5, 2, 10, 10, 12, 35, 36, 36, 2, 2, 4, 7, 8
  )
)

然后,

subseted_Spcount = 0
plot = 0
for (i in unique(Spcount$Species)) {
  subseted_Spcount = subset(Spcount, Species == i)
  plot <- ggplot(subseted_Spcount, aes(x = Size.Class)) +
    geom_histogram(binwidth = 5) +
    ggtitle(paste0(i, " Histogram")) +
    labs(y= "Total Count", x = "Size Class")
  print(plot)
}

不要忘记使用Next plot (Ctrl + Alt + F12)Previous plot (Ctrl + Alt + F11)查看不同的直方图。


推荐阅读