【发布时间】:2021-03-08 03:28:33
【问题描述】:
我有
-
一个data.frame
dfdf = data.frame(year=c(2018,2019,2020), value1=rnorm(3,1,0.5), value2=rnorm(3,2,0.5) -
一个名为 ScatterPlot 的 ggplot 函数(函数代码见下文)
-
一个
for loop,我想用它在我的df上运行ggplot函数
我的意图是自动(使用 scatterplot 函数和我的 for 循环)绘制(散点)多年来的 value1 和多年的 value2。
由于某种原因,下面的 for 循环仅生成一个图(我的 df 中的最后一个)。谁能告诉我我错过了什么?
for循环:
# Create the loop.vector (all the columns)
loop.vector <- ncol(df)-1
for (i in loop.vector) { # Loop over loop.vector
# store data in column.i as x
x <- df[i]
x = unlist(x) #necessary. otherwise ggplot will generate an error
plotname = colnames(df[i])
#plot
jpeg(filename=paste0("/R-Outputs/plots/",plotname,".jpeg"))
plot= ScatterPlot(df,df$year,"year", x, plotname)
print(plot)
dev.off()
}
散点图函数(可行):
ScatterPlot <- function(df, x, x_var_label,y, y_var_label) {
# Input:
# df: a data frame
# x: a column from df in the form of a character vector
# y: a column from df in the form of a character vector
#
# Output:
# a ggplot2 plot
require(ggplot2)
x_title = x_var_label
y_title = y_var_label
time_labels = c("2018", "2019", "2020")
ggplot(data = df, aes(x = x, y = y)) +
geom_point(col="#69b3a2",fill="#69b3a2",alpha=0.5, size = 0) +
geom_line()+
geom_smooth(method = "lm", se = FALSE, size = 0.8, col="red") +
xlab(label = x_title) +
ylab(label = y_title) +
theme_bw()+
theme(axis.text.x=element_text(angle=45, hjust = 1))+
labs(title = paste0(y_title," over time"))+
scale_x_continuous("year", labels = as.character(time_labels),
breaks = as.integer((time_labels)))
}
【问题讨论】:
-
试试这个
loop.vector <- seq_len(ncol(df))[-1]