Leni Ohnesorge
Leni Ohnesorge

Reputation: 726

Add geom_vline using function where xintercept comes from a vector not ggplot data

I would like to draw multiple verical lines on a ggplot, which positions come from a separate vector.

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)

Adding them one by one works, but I would like to avoid such approach add use draw_vline instead:

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])

This gives me error:

Error in eval(expr, envir, enclos) : object 'line_value' not found

How can I specify my function to work with external vector which isn't in ggplot env?

Upvotes: 1

Views: 2091

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78832

aes() is for mapping data from columns in the data frame. You don't have a data frame and the _vline/_hline//_abline even show that the default use of xintercept, yintercept, slope & intercept is outside aes(). This works fine in aes(), too, provided you supplied the call with data set, but you didn't.

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) 

enter image description here

Upvotes: 6

Related Questions