我想在 ggplot 中创建动态 ylim 值,以便 ylim 参数引用 dplyr 通过管道提供的值。为了说明问题,请查看我想将其更改为(当前无法正常工作的通用)代码的工作(非通用)代码。
require(dplyr)
require(scales)
require(ggplot2)
x <- data.frame(name = c("A","B","C"),
value = c(2,4,6))
工作非通用代码:
arrange(x[1:2, ], value) %>%
ggplot(data=., aes(x=factor(name), y=value)) +
geom_bar(stat="identity") +
scale_y_continuous(labels=comma,
limits=c(0,max(arrange(x[1:2, ], value)$value) * 1.1))
不工作的通用代码(调用找不到值):
arrange(x[1:2, ], value) %>%
ggplot(data=., aes(x=factor(name), y=value)) +
geom_bar(stat="identity") +
scale_y_continuous(labels=comma,
limits=c(0,max(value) * 1.1))
所以问题是是否有任何方法可以设置通常的限制,即排列后的部分将始终相同(我需要生成许多具有不同 x 的相同图形,即不同的限制)。
谢谢!
最佳答案
如果你能忍受使用 <<-
并且不介意使用一个额外的变量,以下将保留管道并为您提供动态 ylim
:
max_val <- 0
arrange(x[1:2, ], value) %>%
{ max_val <<- max(.$value)
. } %>%
ggplot(data=., aes(x=factor(name), y=value)) +
geom_bar(stat="identity") +
scale_y_continuous(labels=comma,
limits=c(0, max_val * 1.1))
关于r - 使用 dplyr 管道在 ggplot2 中动态 ylim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29121995/