将ggplots存储为R中的“变量”

时间:2018-11-26 15:12:36

标签: r ggplot2

我的数据帧如下:

tt <- as.POSIXct("20180810 00:00:01", format = "%Y%m%d %H:%M:%S")
tts <- seq(tt, by = "hours", length = 6)

df.1 <- data.frame(tts, t=c(10,20,30, NA, 15, 12), hr=c(0,1,2, NA, 4, 5))
df.2 <- data.frame(tts, t=c(14,NA,9, 2, NA, NA), hr=c(0,1,NA, 3, 4, 5))

分别绘制两个df可以正常工作,并且符合预期!:

ggplot(subset(df.1, !is.na(t))) +
geom_point(mapping = aes(tts, hr, fill = t) ,shape = 22, size = 5) +
scale_fill_gradient(low="green", high="red")

ggplot(subset(df.2, !is.na(t))) +
geom_point(mapping = aes(tts, hr, fill = t) ,shape = 22, size = 5) +
scale_fill_gradient(low="green", high="red")

但是我想做某事,就像我在下面尝试并“存储地块”一样,这样我以后就可以对它们以及其他地块进行绘图了……:

for (count in seq(from = 1,to = 2, by =1)){
pk<-paste0("df."count)

assign("pl."count) <- ggplot(subset(pk, !is.na(t))) +
geom_point(mapping = aes(tts, hr, fill = t) ,shape = 22, size = 5) +
scale_fill_gradient(low="green", high="red")
...

}

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

我个人非常喜欢为此使用小技巧。这些是类似于数据框架的结构,还允许您存储其他数据框架或在其中绘制对象。这还允许您将数据框映射到绘图功能上,并立即将其存储在小标题中。例如,使用您提供的数据:

library(tidyverse)
plots_tib <- tibble(data = list(df.1, df.2)) %>% 
  mutate(plots = map(data, function(df){
                    ggplot(subset(df, !is.na(t))) +
                      geom_point(mapping = aes(tts, hr, fill = t) ,shape = 22, size = 5) +
                      scale_fill_gradient(low="green", high="red")}))

这将导致此提示:

plots_tib
# A tibble: 2 x 2
  data                 plots   
  <list>               <list>  
1 <data.frame [6 × 3]> <S3: gg>
2 <data.frame [6 × 3]> <S3: gg>

如果您想从小标题中绘制所有图,只需运行plots_tib$plots

如果您需要将更多变量映射到ggplot函数(例如,您可以在小标题中添加颜色列并使用它),请查看?map2

请注意,我加载了tidyverse库,其中包括tibble,还有我在答案中使用的其他一些功能。

相关问题