我有一个要用ggplot绘制的数据帧列表(df_list)。我想在x刻度上显示日期(当然,它总是相同),然后在2个不同的geo_lines上显示。 df1-3中的第一个地线和abc中的第二个地线。这是一个代码示例:
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")
例如,我想将df_list$df1$df1_Tmax
与df_list$abc$ABC_Tmax
一起绘制。
我尝试过:
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")
但是我收到此错误消息:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a list
有什么办法解决这个问题吗?
答案 0 :(得分:1)
您可以尝试一下。
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")
只需使用cbind
函数中的cbind(df_list$df1, df_list$abc)
,即ggplot
生成新的数据帧。
注意:
cbind(df_list$df1, df_list$abc)
导致以下错误。
错误:
data
必须具有唯一的名称,但具有重复的列
请尝试执行此操作,因为在这两个数据框中也有相同的Date
变量。