lapply 在 Ggplot 中创建多个图的函数
lapply function to create many plots in Ggplot
我正在尝试绘制 X=date Y=column 的折线图,即 XS1-XS10。
我将 lapply 与 next 函数一起使用
plot_data_column = function (column) {
ggplot(data= excess_return, aes(y=column,x=date)) +
geom_line()+
geom_hline(yintercept = mean(excess_return$column), color="red")+
ggtitle(column)+
theme_minimal()
}
然后使用 lapply 将数据集的列插入到 ggplot 中。
ggplots = lapply(excess_return[,1:10], plot_data_column)
我的问题出现在 geom_hline 上,它无法识别列和 ggtitle(column)。
P.s我也试过这样
ggplots = lapply(colnames(excess_return[,1:10]), plot_data_column)
我想知道为什么 R 不接受我手动编写的 XS1?
因为此代码完美运行。
ggplot(data= excess_return, aes(y=XS1,x=date)) +
geom_line()+
geom_hline(yintercept = mean(excess_return$XS1), color="red")+
theme_minimal()
我唯一想要做的就是将 XS1 迭代到 XS10。
感谢支持
您可以根据您的数据结构调整它:
plot_data_column = function (.data, .column) {
ggplot2::ggplot(data= .data, ggplot2::aes(y=!!dplyr::sym(.column),x = Petal.Width)) +
ggplot2::geom_line() +
ggplot2::geom_hline(yintercept = .data %>%
dplyr::pull(!!dplyr::sym(.column)) %>%
mean(),
color="red")+
ggplot2::ggtitle(.column) +
ggplot2::theme_minimal()
}
plots <- names(iris)[1:3] %>%
purrr::map(~plot_data_column(.data = iris, .column = .x))
您需要将 names(iris)[1:3]
更改为您的名字 names(excess_return)[1:10]
并将 x = Petal.Width
更改为 x = date
。
我正在尝试绘制 X=date Y=column 的折线图,即 XS1-XS10。 我将 lapply 与 next 函数一起使用
plot_data_column = function (column) {
ggplot(data= excess_return, aes(y=column,x=date)) +
geom_line()+
geom_hline(yintercept = mean(excess_return$column), color="red")+
ggtitle(column)+
theme_minimal()
}
然后使用 lapply 将数据集的列插入到 ggplot 中。
ggplots = lapply(excess_return[,1:10], plot_data_column)
我的问题出现在 geom_hline 上,它无法识别列和 ggtitle(column)。 P.s我也试过这样
ggplots = lapply(colnames(excess_return[,1:10]), plot_data_column)
我想知道为什么 R 不接受我手动编写的 XS1? 因为此代码完美运行。
ggplot(data= excess_return, aes(y=XS1,x=date)) +
geom_line()+
geom_hline(yintercept = mean(excess_return$XS1), color="red")+
theme_minimal()
我唯一想要做的就是将 XS1 迭代到 XS10。
感谢支持
您可以根据您的数据结构调整它:
plot_data_column = function (.data, .column) {
ggplot2::ggplot(data= .data, ggplot2::aes(y=!!dplyr::sym(.column),x = Petal.Width)) +
ggplot2::geom_line() +
ggplot2::geom_hline(yintercept = .data %>%
dplyr::pull(!!dplyr::sym(.column)) %>%
mean(),
color="red")+
ggplot2::ggtitle(.column) +
ggplot2::theme_minimal()
}
plots <- names(iris)[1:3] %>%
purrr::map(~plot_data_column(.data = iris, .column = .x))
您需要将 names(iris)[1:3]
更改为您的名字 names(excess_return)[1:10]
并将 x = Petal.Width
更改为 x = date
。