Reputation: 99
I have data frames as follows:
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))
Plotting both df´s individually works fine and as expected!:
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")
But I´d like to do sth like I tried below and "store plots", so that I could plot these, and other plots later...sth like: :
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")
...
}
Any ideas?
Thanks in advance!
Upvotes: 1
Views: 1645
Reputation: 1445
Personally I am a big fan of using tibbles for this. These are data frame-like structures that also allow you to store other data frames or plot objects in them. This also allows you to map your data frames onto your plot function and immediately store it in the tibble. For instance, using the data you provided:
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")}))
which results in this tibble:
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>
If you then want to plot all plots from your tibble, simply run plots_tib$plots
.
In case you need to map more variables to your ggplot function (you can for instance add a color column to the tibble and use that), take a look at ?map2
.
Note that I loaded the tidyverse library, which includes tibble, but also some other functions I have used in the answer.
Upvotes: 2