在 R 中使用 for 循环绘制多个图
Posted
技术标签:
【中文标题】在 R 中使用 for 循环绘制多个图【英文标题】:Plot multiple plots with a for loop in R 【发布时间】:2022-01-05 09:46:36 【问题描述】:我正在尝试从数据集中绘制一些线图,但在列表 var 中设置了不同的 y 轴值。出于某种原因,所有图似乎都显示一个空图,但是当我有相同的代码而没有 for 循环时,它似乎可以工作。所以我的问题是我是否可以使用 for 循环一次绘制多个图,而不是单独绘制它们。我在绘制这个时是否遗漏了什么。
var = list("CAH", 'CTLT',"CI","DVA","HSIC","HOLX","HUM","IDXX","INCY","MRK","REGN","VTRS")
for(v in var)
p<-closing_price %>%
mutate(date = as.Date(Date,"%m/%d/%y")) %>%
ggplot(aes(x = date, y = v, group=1)) +
geom_line() +
labs(x = "Date", y = "Stock Price ($)", title = glue("v price over time")) +
scale_x_date(date_minor_breaks = "2 day")
print(p)
这是我正在寻找的结果:
closing_price %>%
mutate(date = as.Date(Date,"%m/%d/%y")) %>%
select(date,CAH) %>%
ggplot(aes(x = date, y = CAH, group=1)) +
geom_line() +
labs(x = "Date", y = "Stock Price ($)", title = "CAH price over time") +
scale_x_date(date_minor_breaks = "2 day")
【问题讨论】:
v
是一个字符。这就是为什么你会得到一条水平线。试试y = .data[[v]]
。参见例如fishandwhistle.net/slides/rstudioconf2020/#7.
【参考方案1】:
正如 stefan 所指出的,ggplot 认为您正在尝试绘制角色,这就是您在 y 轴上获得“CAH”的原因。您可以使用.data[[v]]
引用变量。
var = list("CAH", 'CTLT',"CI","DVA","HSIC","HOLX","HUM","IDXX","INCY","MRK","REGN","VTRS")
for(v in var)
p<-closing_price %>%
mutate(date = as.Date(Date,"%m/%d/%y")) %>%
ggplot(aes(x = date, y = .data[[v]], group=1)) +
geom_line() +
labs(x = "Date", y = "Stock Price ($)", title = glue("v price over time")) +
scale_x_date(date_minor_breaks = "2 day")
print(p)
由于我无权访问您的数据,这里有一个可重现的示例:
library(tidyverse)
library(zoo)
closing_price <-
tibble(
dt = as.Date(seq(as.yearmon("2020-01-31"), as.yearmon("2020-12-31"), by = 1 / 12), frac = 1),
CAH = rnorm(12, mean = 10, sd = 2),
CTLT = rnorm(12, mean = 50, sd = 5),
CI = rnorm(12, mean = 25, sd = 2)
)
vars <- c("CAH", "CTLT","CI")
for(v in vars)
p <-
ggplot(data = closing_price, aes(x = dt, y = .data[[v]])) +
geom_line() +
labs(x = "Date", y = "Stock Price ($)", title = paste(v, "price over time")) +
scale_x_date(date_minor_breaks = "2 day")
print(p)
您也可以使用lapply
来代替将您的情节包装在一个函数中。该功能可能很有用,具体取决于您制作这些图的频率或使其更易于修复和共享。
closing_price_plot <- function(data, var)
p <-
data %>%
ggplot(aes(x = dt, y = .data[[var]], group=1)) +
geom_line() +
labs(x = "Date", y = "Stock Price ($)", title = paste(var, "price over time")) +
scale_x_date(date_minor_breaks = "2 day")
return(p)
## prints out the plots as in the loop
lapply(vars, FUN = closing_price_plot, data = closing_price)
## save them to a list instead
p <- list()
p <- lapply(vars, FUN = closing_price_plot, data = closing_price)
## view the first plot
p[[1]]
【讨论】:
以上是关于在 R 中使用 for 循环绘制多个图的主要内容,如果未能解决你的问题,请参考以下文章
R语言使用for循环绘制多个模型的DCA(Decision Curve Analysis)曲线并保存特定分辨率的DCA曲线的结果文件