gpt4 book ai didi

r - 将绘图分配给循环中的变量

转载 作者:行者123 更新时间:2023-12-02 12:34:30 24 4
gpt4 key购买 nike

我正在尝试创建 2 条线图。

但我注意到使用 for 循环将生成两个带有 y=mev2 的图(而不是基于 y=mev1 的图)另一个基于 y=mev2)。

下面的代码显示了此处的观察结果。

mev1 <- c(1,3,7)
mev2 <- c(9,8,2)
Period <- c(1960, 1970, 1980)
df <- data.frame(Period, mev1, mev2)

library(ggplot2)
# Method 1: Creating plot1 and plot2 without using "for" loop (hard-code)
plot1 <- ggplot(data = df, aes(x=Period, y=unlist(as.list(df[2])))) + geom_line()
plot2 <- ggplot(data = df, aes(x=Period, y=unlist(as.list(df[3])))) + geom_line()

# Method 2: Creating plot1 and plot2 using "for" loop
for (i in 1:2) {
y_var <- unlist(as.list(df[i+1]))
assign(paste("plot", i, sep = ""), ggplot(data = df, aes(x=Period, y=y_var)) + geom_line())
}

似乎这是由于我不知道的一些 ggplot() 工作方式造成的。

问题:

  • 如果我想使用方法2,我应该如何修改逻辑?
  • 人们说使用 assign() 不是“R 风格”,所以我想知道有什么替代方法可以做到这一点?比如说,使用list

最佳答案

没有添加 tidyverse 命令的一个可能答案是:

library(ggplot2)

y_var <- colnames(df)
for (i in 1:2) {
assign(paste("plot", i, sep = ""),
ggplot(data = df, aes_string(x=y_var[1], y=y_var[1 + i])) +
geom_line())
}

plot1
plot2

您可以使用aes_string。我希望它有帮助。

编辑 1

如果你想将你的情节存储在列表中,你可以使用这个:

初始化您的列表:

n <- 2 # number of plots
list_plot <- vector(mode = "list", length = n)
names(list_plot) <- paste("plot", 1:n)

填写:

for (i in 1:2) {
list_plot[[i]] <- ggplot(data = df, aes_string(x=y_var[1], y=y_var[1 + i])) +
geom_line()
}

显示:

list_plot[[1]]
list_plot[[2]]

关于r - 将绘图分配给循环中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com