我正在尝试创建一个函数,该函数将使用ggplot2
绘制多个参数。我希望能够遍历每个参数并将其绘制为plotlist
定义的线图或点图。
在下面的代码中,如果希望将参数绘制为“点”,则可以通过
geom_point(aes(x = as.POSIXct(df$date, origin = "1970-01-01"), y =df[,y_col[i]],
color = param_list[i]),size = 1,alpha = 1)
到变量point_geom
。问题在于变量(即y_col[i]
,param_list[i]
)发生了变化,因此唯一的细图是循环中的最后一个参数。
我尝试将point_geom
转换为字符串,但这也不起作用。
param_list = c("Wind Speed","Wind Speed","Wind Gust") #parameters I want plotted
units = c("kts","kts","kts") #units of the parameters
plotlist= c("point", "line", "point") #type of plot I want generated
y_col = c(3,3,4) # column of the data frame where data is located
for ( i in i:length(plotlist)) {
if (plotlist[i] == "point") {
point_geom = geom_point(aes(x = as.POSIXct(df$date, origin = "1970-01-01"),
y =df[,y_col[i]], color = param_list[i]),
size = 1, alpha = 1)
my_geoms[i] <-c(point_geom)
} else if (plotlist[i] == "line") {
line_geom = geom_line(aes(x = as.POSIXct(df$date, origin = "1970-01-01"),
y =df[,y_col[i]], color = param_list[i]),
size = 1, alpha = 1)
my_geoms[i] <- c(line_geom)
}
}
ggplot(data = df) + my_geoms #plot aesthetics formatting
以上内容的最终图应如下所示: Rplot