我的问题类似于 this one (我想对轴上的标签使用任意文本),而不是将值硬编码到 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()}
这有效,但感觉像是一种解决方法。有没有规范/正确/更清洁/更好的方法来做到这一点?我一直试图在文档中找到答案,但我无法找到正确的关键字来描述这种情况。
(剧情是胡说八道,我知道。)
最佳答案
一个有趣的问题。 +1
我还没有一个完美的答案,但如果你准备放弃 tibble 创建和绘图之间的管道,我可以提供一些简化。
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()
如果 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)
这种方法至少尊重 tidyverse 对 NSE 的使用,因此自然适合 magrittr 的管道框架,但最好避免使用自定义函数。我还没有弄清楚如何从 ggplot“%>%
管道”中回溯到“+
管道”的起源。您可以扩展
myPlot
函数以明显的方式处理任意 x 和 y 变量。
关于r - 在 ggplot 比例函数中引用数据集变量的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980838/