mpettis - 10 months ago 59

R Question

I'd like to parameterize a series of functions for the

`ggplot2`

I am trying to capture and pass on a parameter value to

`geom_vline()`

`geom_text()`

`markvline()`

`markvline()`

`qplot()`

`geom_vline() + geom_text()`

I assume I need to understand quote/eval/substitute a bit better, but I don't at this point. Any help is appreciated as to how I would construct

`markvline()`

`geom_vline() + geom_text()`

`library(ggplot2)`

## This works

## Making labeled vertical lines at 5 and 6

qplot(Sepal.Length, Sepal.Width, data=iris) +

geom_vline(xintercept=5, color="red", size=1) +

geom_text(x=5, y=4, label="5", hjust=0) +

geom_vline(xintercept=6, color="red", size=1) +

geom_text(x=6, y=4, label="6", hjust=0)

## I would like to parameterize these two statements

markvline <- function(e) {

geom_vline(xintercept=e, color="red", size=1) +

geom_text(x=e, y=4, label=as.character(e), hjust=0)}

## ... but this does not work

qplot(Sepal.Length, Sepal.Width, data=iris) +

markvline(5) +

markvline(6)

Answer Source

The best I was able to do is:

```
markvline <- function(e) {
list(geom_vline(xintercept=e, color="red", size=1),
geom_text(x=e, y=4, label=as.character(e), hjust=0))}
qplot(Sepal.Length, Sepal.Width, data=iris) +
markvline(5) + markvline(6)
```