在 ggplot 比例函数中引用数据集变量的正确方法是什么?

los*_*ost 6 r ggplot2

我的问题与此类似(我想对轴上的标签使用任意文本),但ggplot我不想将值硬编码到函数中,而是想通过引用源数据集中存在的变量来提供它们。

我一直使用的解决方案是将所有ggplot代码包装在大括号内,将源数据集通过管道传输到其中,并使用以下方式引用变量.$

library(tidyverse)

tribble(
  ~description, ~y, ~x,
  "apples", 3.4, 1.1,
  "oranges", 5.6, 2.4,
  "mangos", 2.3, 4.8
) %>%
  {ggplot(data = ., aes(y = y, x = x)) +
      scale_x_continuous(
        breaks = .$x,
        labels = .$description
      ) +
      geom_point() + geom_line()}
Run Code Online (Sandbox Code Playgroud)

这可行,但感觉像是一种解决方法。有没有规范/正确/更干净/更好的方法来做到这一点?我一直试图在文档中找到答案,但无法找到正确的关键字来描述这种情况。

(我知道这个情节是胡说八道。)

Lim*_*mey 2

一个有趣的问题。+1

我还没有一个完美的答案,但如果您准备放弃小标题创建和绘图之间的管道,我可以提供一些简化。

d <- tribble(
  ~description, ~y, ~x,
  "apples", 3.4, 1.1,
  "oranges", 5.6, 2.4,
  "mangos", 2.3, 4.8
) 

d %>% ggplot(aes(y = y, x = x)) +
        scale_x_continuous(breaks = d$x, labels = d$description) +
        geom_point() + geom_line()
Run Code Online (Sandbox Code Playgroud)

如果 tibble 创建的管道很重要,您可以将绘图创建包装在一个函数中:

myPlot <- function(data, labels, breaks) {
  bVar <- enquo(breaks)
  lVar <- enquo(labels)
  data %>% ggplot(aes(y = y, x = x)) +
    scale_x_continuous(breaks = data %>% pull(!! bVar), labels = data %>% pull(!! lVar)) +
    geom_point() + geom_line()
}

tribble(
  ~description, ~y, ~x,
  "apples", 3.4, 1.1,
  "oranges", 5.6, 2.4,
  "mangos", 2.3, 4.8
) %>% myPlot(description, x)
Run Code Online (Sandbox Code Playgroud)

这种方法至少尊重 tidyverse 对 NSE 的使用,因此自然适合 magrittr 的管道框架,但最好避免使用自定义函数。%>%我还没有弄清楚如何从 ggplot“pipe”中引用“pipe”的起源+

您可以扩展该myPlot函数以以明显的方式处理任意 x 和 y 变量。