【问题标题】:R - Error when saving multiple plots in a loopR - 在循环中保存多个图时出错
【发布时间】:2020-02-14 12:16:27
【问题描述】:

我有一个像这个测试框架这样的数据框架,但要大得多。

lat_area = seq (50, 40, -0.5)
lon_area = seq (-10, 10, 0.5)
grid_area = matrix(0, ncol=2, nrow=length(lon_area)*length(lat_area))
grid_area[,2] = rep(lat_area, each=length(lon_area))
grid_area[,1] = lon_area
testframe = as.data.frame(grid_area)

colnames(testframe) = c("Lon", "Lat")
testframe$FDsw = rep(c(0.5,0.7), length.out= nrow(testframe))
testframe$Thgf = rep(c(0.2,0.3), length.out= nrow(testframe))
testframe$Igbff = rep(c(0.8,0.9), length.out= nrow(testframe))

我想为每个数据列制作等高线图(测试帧中的列 3:5) 我发现了多个关于如何自动保存多个图的问题。我认为最好的方法是将所有图保存在一个列表中,然后再从这个列表中保存它们。我的尝试在下面。

library(ggplot2)
library(metR)

plot_list = list()
for (i in 3:length(testframe)) {
  wd = map_data("world") 
  LP = ggplot() 
  LP = LP + 
    geom_contour_fill(data = testframe, aes(x = Lon, y = Lat, z = colnames(testframe)[i]), breaks = MakeBreaks(0.1)) + 
    geom_contour(data = testframe, aes(x = Lon, y = Lat, z = colnames(testframe)[i]), color = "blue", size = 0.6) + 
    geom_text_contour(data = testframe, aes(x = Lon, y = Lat, z = colnames(testframe)[i]), stroke = 0.1) + 
    scale_fill_divergent() +
    geom_polygon(data = wd , aes(x = long, y = lat, group = group), colour="black", fill = NA) + 
    coord_cartesian(xlim = c(-10, 10), ylim = c(50, 40)) +
    scale_x_longitude(ticks = 10)+ scale_y_latitude(ticks = 10) +
    labs(title= paste("Plot", colnames(testframe)[i], sep = " ")) 
  plot_list[[i]] = LP}

plot_list[1:2] = NULL
names(plot_list) = colnames(testframe)[3:ncol(testframe)]


for (i in 1:3) {
  file_name = paste("Plot", i, ".tiff", sep="")
  tiff(file_name)
  print(plot_list[[i]])
  dev.off()
}           

我不知道我做错了什么。我收到此错误:

Error in UseMethod("fullseq") : 
  no applicable method for 'fullseq' applied to an object of class "character"
In addition: Warning message:
In pretty.default(range(data$z, na.rm = TRUE), 10) :
  NAs introduced by coercion

有谁知道为什么这不起作用?

【问题讨论】:

标签: r loops ggplot2 plot


【解决方案1】:

您不能将变量插入到常规的aes() 语句中,因为它们是在打印时进行评估的。您需要传递 sumbols 而不是字符串,并且变量未包含在绘图对象中。所以像

aes(x = Lon, y = Lat, z = colnames(testframe)[i])

行不通。使用最新版本的 ggplot2,您可以使用 rlang::sym()!!(bang bang)运算符的组合将符号插入到表达式中。试试

aes(x = Lon, y = Lat, z = !!rlang::sym(colnames(testframe)[i]))

【讨论】:

  • 感谢您的回答。我仍然收到错误:错误:意外符号在:“实验室(标题=粘贴(“绘图”,colnames(测试帧)[i],sep =“”))plot_list”> > plot_list [1:2] = NULL>名称(plot_list) = colnames(testframe)[3:ncol(testframe)] 名称错误(plot_list) = colnames(testframe)[3:ncol(testframe)] : 'names' 属性 [3] 必须与向量 [0] > > > for (i in 1:3) { + file_name = paste("Plot", i, ".tiff", sep="") + tiff(file_name) + print(plot_list[[i] ]) + dev.off() + } plot_list[[i]] 中的错误:下标超出范围
  • 你确定你得到了上面的代码和数据吗?我只是按照我建议的更改运行它,并没有收到该错误。
  • 好吧,好像我做错了!现在它正在运行!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2018-09-24
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 2020-05-30
相关资源
最近更新 更多