我正在嘗試繪制 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)。Ps我也試過這樣
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。

謝謝你的支持
uj5u.com熱心網友回復:
您可以將其調整為您的資料結構:
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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358865.html
