本文介绍了如何在lapply期间将ggplot x标签设置为等于变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制一个y变量相对于多个x变量的图.我有一个使用lapply的有效解决方案.但是,我无法将x变量的名称写为每个图的x标签.这是我所拥有的简化示例:

I'm making plots of one y variable against multiple x variables.I have a working solution using lapply. However, I can't manage to write the name of the x variable as the x label for each plot. Here's a simplified example of what I have:

目标是针对每个x变量绘制y变量,从而得出三幅图,并将每个x变量的名称添加为x轴标签.

The goal is to plot the y variable against each x variable resulting in three plots and adding the name of each x variable as the x axis label.

生成具有一个y变量和三个x变量的数据框:

df <- data.frame(y.variable=c(11:20), x1=c(21:30),x2=c(1:10),x3=c(31:40))

应该以字符串形式检索变量名称的函数:

get_name <- function(v1) {deparse(substitute(v1))}

针对x变量生成y图的函数:

generate_plot <- function(x.variable) {ggplot(data = df, aes(x.variable, y.variable )) +geom_point()  + xlab(get_name(variable.name))}

调用lapply在df的每一列上执行generate_plot:

lapply(df, generate_plot)

这将导致三个图,每个图的x标签都带有"variable.x",而不是所需的变量名称x1,x2和x3.

This results in three plots, each of which has "variable.x" as its x-label instead of the desired variable name x1, x2 and x3.

推荐答案

我稍微修改了您的generate_plot并使用了 ggplot2 (> v3.0.0),它支持tidy evaluation

I modify your generate_plot a little bit and use the version of ggplot2 (> v3.0.0) which supports tidy evaluation

说明:

  • 在函数内部,我们使用rlang::sym将字符串转换为符号,然后在aes内部使用!!(爆炸)

  • Inside the function, we use rlang::sym to turn a string into a symbol then unquote it inside aes using !! (bang bang)

要调用该函数,请使用purrr::map遍历df列名

To call the function, use purrr::map to loop through df column names

查看更多:

  • https://dplyr.tidyverse.org/articles/programming.html
  • http://rlang.r-lib.org/reference/quotation.html
library(tidyverse)

df <- data.frame(y.variable=c(11:20), 
                 x1=c(21:30), x2=c(1:10), x3=c(31:40))

generate_plot2 <- function(df, x.variable) {
  x.variable <- rlang::sym(x.variable)

  ggplot(data = df, aes(!! x.variable, y.variable )) +
    geom_point() + 
    xlab(x.variable)
}

names(df)[-1] %>% 
  map(~ generate_plot2(df, .x))

这篇关于如何在lapply期间将ggplot x标签设置为等于变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:53