Essi
Essi

Reputation: 801

R Using ggplot with a list of dataframes

I have a list of dataframes (df_list) which I want to plot with ggplot. I want to display the Date on the x-scale (its always the same of course) and then 2 different geo_lines. The first geoline out of the df1-3 and the 2nd line from abc. Here is an examle code:

library(lubridate)
v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,7, length = 10)
v4 = seq(-6,3, length = 10)
df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(3,21, length = 10)
v3 = seq(-3,8, length = 10)
v4 = seq(-7,4, length = 10)
df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(4,22, length = 10)
v3 = seq(-4,9, length = 10)
v4 = seq(-8,5, length = 10)
df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,8, length = 10)
v4 = seq(-6,3, length = 10)
abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

df_list = list(df1, df2, df3, abc)
names(df_list) = c("df1", "df2", "df3", "abc")

For example I want to plot df_list$df1$df1_Tmax together with df_list$abc$ABC_Tmax.

I tried this:

ggplot(data = df_list, aes(x = df1$Date)) +
  geom_line(aes(y = df1$df1_Tmax), color = "darkgreen", size = 1) +
  geom_line(aes(y = abc$ABC_Tmax), color = "grey27", size = 1) +
  labs(title="Title", 
       subtitle="subtitle", 
       x = "day", 
       y = "T") +
  scale_x_date(date_labels="%d",date_breaks  ="1 day")

But I get this error message:

Error: `data` must be a data frame, or other object coercible by `fortify()`, not a list

Any ideas how to solve this problem?

Upvotes: 0

Views: 5135

Answers (1)

HCQ
HCQ

Reputation: 96

You can try this.

library(ggplot2)
ggplot(data = cbind(df_list$df1, df_list$abc), aes(x = Date)) +
  geom_line(aes(y = df1_Tmax), color = "darkgreen", size = 1) +
  geom_line(aes(y = ABC_Tmax), color = "grey27", size = 1) +
  labs(title="Title", 
       subtitle="subtitle", 
       x = "day", 
       y = "T") +
  scale_x_date(date_labels="%d",date_breaks  ="1 day")

Just generate a new data frame using cbind, i.e., cbind(df_list$df1, df_list$abc) within ggplot function.

Caution: cbind(df_list$df1, df_list$abc) leads to the following error.

Error: data must be uniquely named but has duplicate columns

Please try this since you also have the same Date variable in these two data frames.

Upvotes: 1

Related Questions