我想在 ggplot 上绘制多条垂直线,这些位置来自单独的向量。
library(ggplot2)
carats <- c(2.5, 0.1)
ggplot(diamonds, aes(carat)) +
geom_histogram() +
geom_vline(aes(xintercept = carats[1]), col = "black", linetype = "dotted", size = 0.5) +
geom_vline(aes(xintercept = carats[2]), col = "black", linetype = "dotted", size = 0.5)
Run Code Online (Sandbox Code Playgroud)
一一添加它们是可行的,但我想避免这种方法添加使用draw_vline:
hist <- ggplot(diamonds, aes(carat)) + geom_histogram()
draw_vline <- function(histogram, line_value){
hist + geom_vline(aes(xintercept = line_value), col = "black", linetype = "dotted", size = 0.5)
}
draw_vline(hist, carats[1])
Run Code Online (Sandbox Code Playgroud)
这给了我错误:
Error in eval(expr, envir, enclos) : object 'line_value' not found
如何指定我的函数来使用不在 ggplot 环境中的外部向量?
aes()用于映射数据框中的列数据。您没有数据框,并且_vline//甚至显示, , &_hline/的_abline默认使用
是在外部。如果您使用 set 提供了调用,那么这在 中也可以正常工作,但您没有。xinterceptyinterceptslopeintercept aes()aes()data
library(ggplot2)
carats <- c(2.5, 0.1)
ggplot(diamonds, aes(carat)) +
geom_histogram() +
geom_vline(xintercept = carats, col = "black", linetype = "dotted", size = 0.5)
Run Code Online (Sandbox Code Playgroud)