我想找到一种方法来创建图表并在一个命令运行中打印它,这样我就不必每次在绘图中进行微小更改时来回移动光标。这是一个例子。
data <- data.frame(
x = runif(5),
y = runif(5)
)
graph <- data %>%
ggplot(aes(x = x, y = y)) +
geom_point()
print(graph)
现在,我分两步运行图表:一次按 Ctrl+Enter 创建绘图,再按一次 Ctrl+Enter 打印它。
我尝试使用管道运算符和+号,但它们都不起作用:
加号:
graph <- data %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
print(graph)
输出:
Error in `ggplot_add()`:
! Can't add `print(graph)` to a <ggplot> object.
Run `rlang::last_trace()` to see where the error occurred.
管道操作员:
graph <- data %>%
ggplot(aes(x = x, y = y)) +
geom_point() %>%
print()
输出:
geom_point: na.rm = FALSE
stat_identity: na.rm = FALSE
position_identity
所以在这里我只得到命令输出,但没有打印图表。
解决方案是什么?
library(ggplot2)
data <- data.frame(
x = runif(5),
y = runif(5)
)
(graph <- data |>
ggplot(aes(x = x, y = y)) +
geom_point())
创建于 2024-04-18,使用 reprex v2.1.0