r - 在 ggplot2 函数中访问轴标签的变量属性信息

标签 r ggplot2

我正在寻找提高大型数据集数据可视化效率的方法。为此,我使用 ggplot2 创建了几个函数。一些生成的图形可能用于分发,因此,我希望它们具有易于理解的标题和轴标签。我想我可以使用 attr() 将可读标签关联到每个变量。这样我就不必重命名变量和处理包括空格的长变量名。我在使用 ggplot 的函数时成功了

library(ggplot2)
library(magrittr)

# Set attributes
mt <- mtcars
attr(mt$mpg, "desc") <- "Miles per Gallon"   
attr(mt$cyl, "desc") <- "Number of Cylinders"


mt %>% 
  ggplot() +
  geom_point(aes(x = cyl, y = mpg)) +
  labs(x = attr(mt$cyl, "desc"),
       y = attr(mt$mpg, "desc"))

以上代码的行为符合我的预期,并返回包含轴标签的图表。但是,当我创建绘图函数时,我不知道如何访问变量属性。以下两种尝试都成功创建了图形,但是不生成轴标签

vis_1 <- function(.data, .x, .y) {
  .data %>% 
    ggplot() + 
    geom_point(aes(x = {{.x}}, y = {{.y}})) +
    labs(x = attr({{.data$.x}}, "desc"),
         y = attr({{.data$.y}}, "desc"))
}

vis_1(.data = mt, .x = cyl, .y = mpg)

vis_2 <- function(.data, .x, .y) {
  attr_x <- attr(.data$.x, "desc")
  attr_y <- attr(.data$.y, "desc")
  
  .data %>% 
    ggplot() + 
    geom_point(aes(x = {{.x}}, y = {{.y}})) +
    labs(x = attr_x,
         y = attr_y)
}

vis_2(.data = mt, .x = cyl, .y = mpg)

如有任何建议,我们将不胜感激。

最佳答案

这里的问题是quoting您正在传递的变量。

如果您愿意使用 cylmpg 作为带引号的变量,这是一个选项。 attr 中的基础 [ 子集可以正常工作,在 ggplot 中你可以使用 !!sym() .

vis_2 <- function(df, x, y) {
  
  attr_x <- attr(df[,x], "desc")
  attr_y <- attr(df[,y], "desc")
  
  df %>% 
    ggplot() + 
    geom_point(aes(!!sym(x), !!sym(y))) +
    labs(x = attr_x,
         y = attr_y)
}

vis_2(mt, 'cyl', 'mpg')

传递不带引号的变量的版本。此解决方案使用 deparse(substitute(x)) 用于 [ 调用和 !!enquo(x) 用于 ggplot.


vis_3 <- function(df, x, y) {
  
  # base quoting
  x_sub <- deparse(substitute(x))
  y_sub <- deparse(substitute(y))
  
  attr_x <- attr(df[,x_sub], "desc")
  attr_y <- attr(df[,y_sub], "desc")
  
  df %>% 
    ggplot() + 
    geom_point(aes(!!enquo(x), !!enquo(y))) +
    labs(x = attr_x,
         y = attr_y)
}


vis_3(mt, cyl, mpg)

另一个版本使用不带引号的变量,这个版本使用 {{ for ggplotdeparse(ensym() for [.

vis_4 <- function(df, x, y) {
  
  attr_x <- attr(df[,deparse(ensym(x))], "desc")
  attr_y <- attr(df[,deparse(ensym(y))], "desc")
  
  df %>% 
    ggplot() + 
    geom_point(aes({{x}}, {{y}})) +
    labs(x = attr_x,
         y = attr_y)
}


vis_4(mt, cyl, mpg)

关于r - 在 ggplot2 函数中访问轴标签的变量属性信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64054199/

相关文章:

r - gsub ) 仅当没有 (

r - 如何在R中创建连接两点的线

r - 如何根据列名和附加表替换真实值?

用数据帧列表中的唯一序列替换 NA

r - 当我加载 ggfortify 时,自动绘图函数的行为有所不同

r - ggplot2:删除颜色并在条形图中绘制边框

r - 带有 geom_segment 的 x 轴顺序

r - 使用 dplyr 通过多个函数传递列名

r - ggplot2:如何调整箱线图中的填充颜色(并更改图例文本)?

根据值替换轴标签