使用ggplot for loop从一个.csv文件创建和保存不同组的图形

问题描述

如何创建一个循环,该循环将基于.csv文件中的“名称生成并保存45种不同的折线图?

我有一个大的.csv文件,其中包含截至日期的45座不同建筑物的数据。我需要为每个建筑物创建一个折线图,在y轴上显示数字,在x轴上显示日期。

我尝试使用list()让建筑物在循环中使用,但是对于R,实际的建筑物名称太复杂了。

下面的代码产生45个相同的地块,但标题不同。每个图都包含所有数据,而不仅仅是一个建筑物的数据。


# Read in .csv file
d <- read_csv("res_data_ABC.csv")

# Reshape the data to make it longer and omit NA 
d_long <- na.omit(pivot_longer(d,cols = -Name,names_to = "date",values_to = "n"))
print(d_long)
# A tibble: 114 x 3
   Name       date         n
   <chr>      <chr>    <dbl>
 1 Building 1 09/14/20  2030
 2 Building 1 09/21/20 17900
 3 Building 1 09/30/20  1380
 4 Building 2 09/14/20    57
 5 Building 2 09/21/20     0
 6 Building 2 09/28/20   301
 7 Building 3 09/14/20 79200
 8 Building 3 09/21/20 23700
 9 Building 3 09/30/20 21800
10 Building 4 09/16/20   496
# … with 104 more rows

# Begin for loop for each building's plot
for (i in d_long$Name) {
  ggplot(d_long,aes(date,n)) + geom_line() + ggtitle(i) + theme(axis.text.x = element_text(angle = 90)) + ylab("viral density/L") + theme(plot.title = element_text(size = 14,face = "bold",hjust=0.5),axis.title.x = element_text(size = 12,face = "bold"),axis.title.y = element_text(size = 12,face = "bold"))
  ggsave(paste0("~/Desktop/plots/",i,".png"),width = 6,height = 5,units = "cm",dpi=300)
}

这些是产生的图:https://i.stack.imgur.com/5HWI3.png

我不知道如何通过单个建筑物限制每个地块中的数据。

解决方法

在for循环中,您正在使用整个数据框。您应该在for循环中对其进行过滤

for (i in d_long$Name) {
  ggplot(d_long[d_long$Name == i,],aes(date,n)) + geom_line() + ggtitle(i) + theme(axis.text.x = element_text(angle = 90)) + ylab("viral density/L") + theme(plot.title = element_text(size = 14,face = "bold",hjust=0.5),axis.title.x = element_text(size = 12,face = "bold"),axis.title.y = element_text(size = 12,face = "bold"))
  ggsave(paste0("~/Desktop/plots/",i,".png"),width = 6,height = 5,units = "cm",dpi=300)
}