r - 在 lapply 期间将列表对象的名称粘贴到 ggplot 调用中

标签 r ggplot2

我有一个 ggplot-objects 列表

library(ggplot2)
library(gridExtra)
p <- ggplot(mtcars, aes(factor(cyl))) + geom_bar()
plots <- list(p,p,p)
names(plots) <- c("A","B","C")

我可以操纵:

plots <- lapply(plots, function(x) x + theme_bw())
grid.arrange(plots[[1]], plots[[2]], plots[[3]])

这很好用。但是,我不能做的是将 ggplot 对象的名称粘贴到 ggtitle 参数中:

plots <- lapply(plots, function(x) x + ggtitle(paste(names(x))))
grid.arrange(plots[[1]], plots[[2]], plots[[3]])

有些东西被粘贴到参数中,但我基本上错过了正确的层次结构级别:

grid.arrange(plots[[1]], plots[[2]], plots[[3]]) ### all titled "data"
names(plots[[1]][1])
[1] "data"

向上移动层次结构不起作用:

plots <- lapply(plots, function(x) x + ggtitle(paste(names(plots[[x]]))))

 Error in plots[[x]] : invalid subscript type 'list'

我记得一个old question of mine for base-R plotting ,但这不可能转移到这里:

plots <- lapply(names(plots), function(x) plots[[x]] + ggtitle(paste(names(x))))
names(plots)
NULL

我哪里失败了?

最佳答案

这是使用 map 的解决方案:

# Your sample plots
library(ggplot2)
library(gridExtra)
p <- ggplot(mtcars, aes(factor(cyl))) + geom_bar()
plots <- list(p,p,p)
names(plots) <- c("A","B","C")
plots <- lapply(plots, function(x) x + theme_bw())

# Add title to ggplots
plots <- Map(function(gg, title) gg + ggtitle(title), plots, names(plots));
grid.arrange(grobs = plots);

enter image description here

关于r - 在 lapply 期间将列表对象的名称粘贴到 ggplot 调用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50041828/

相关文章:

r - 如何在 R 中抑制 download.file() "trying URL..."消息?

r - 对数刻度 R 上的指数拟合

r - ggplot2(和plyr?)无法绘制

r - 有什么方法可以在 map 上绘制多个条形图?

r - 帮助在 ggplot2 中找到 binwidth 的定义

加载库时 R rgl 包错误

R reshape 性能

r - 如何在气泡图中用不同颜色显示图例中的精确值

r - 如何在R中的递归函数中保持计数?

R plotly : wrong y value with minus values