Use variable name as plot title with lapply

空扰寡人 提交于 2020-01-13 19:13:26

问题


I need to display between 1-3 graphs, and I want the titles of the graphs to be based on the variable name that used.

I can get this to work how I want below:

library(grid)
library(ggplot2)
library(gridExtra)

a1 <- sample(1:100)
a2 <- sample(1:100)
a3 <- sample(1:100)

make_graph <- function(x, y=deparse(substitute(x))){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

g1 <- make_graph(a1)
g2 <- make_graph(a2)
g3 <- make_graph(a3)
grid.arrange(g1,g2,g3)

But this becomes inefficient when I need to include conditional statements if there are only 1 or 2 samples (i.e. only a1, or a1 & a2).

I got everything to work below, with the exception of the correct titles:

library(grid)
library(ggplot2)
library(gridExtra)

a1 <- sample(1:100)
a2 <- sample(1:100)
a3 <- sample(1:100)

sample_list <- paste0("a", seq_len(3))

make_graph <- function(x, y=deparse(substitute(x))){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

graphs_list <- lapply(mget(sample_list), make_graph)
do.call("grid.arrange", graphs_list)

With the above code I get the correct functionality, but deparse() in make_graph() seems to have some issues, I assume due to being called with lapply. So instead of the titles I had in the initial example ("a1", "a2", "a3"), I instead get "X[[1L]]", "X[[2L]]", "X[[3L]]".

I've also tried altering the lapply function, but this only gives me the first "title" in the list:

sample_list <- paste0("a", seq_len(3))

make_graph <- function(x, y){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

graphs_list <- lapply(mget(sample_list), make_graph, y=sample_list)
do.call("grid.arrange", graphs_list)

I'm not sure of the best approach to accomplish what I'm trying to do here. Thanks for any help.


回答1:


You are right about those variable names coming from lapply. So that deparse strategy isn't a good one in that case. But since you made it super easy to pass along the title, you can just use Map rather than lapply.

graphs_list <- Map(make_graph, mget(sample_list), sample_list)
do.call("grid.arrange", graphs_list)

This gives the desired result.



来源:https://stackoverflow.com/questions/23575239/use-variable-name-as-plot-title-with-lapply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!