Tyler Rinker
Tyler Rinker

Reputation: 109874

horizontal line; y axis as factor: ggplot2

If I have a factor for my y variable and try to use geom_hline in facet_grid I get an error:

p <- qplot(mpg, factor(sample(c("a", "b", "c", "d"), nrow(mtcars), T)), data=mtcars, facets = vs ~ am)

hline.data <- data.frame(z = factor(c("a", "b", "c", "d")), vs = c(0,0,1,1), am = c(0,1,0,1))
p + geom_hline(aes(yintercept = z), hline.data)

## > p + geom_hline(aes(yintercept = z), hline.data)
## Error in x - from[1] : non-numeric argument to binary operator

Why do I get the error and how can I fix it?

PS I can fix it by turning it to numeric as in:

hline.data <- data.frame(z = factor(c("a", "b", "c", "d")), vs = c(0,0,1,1), am = c(0,1,0,1))

qplot(mpg, as.numeric(factor(sample(c("a", "b", "c", "d"), nrow(mtcars), T))), data=mtcars, facets = vs ~ am) + 
    geom_hline(aes(yintercept = as.numeric(z)), hline.data)

But I lose the desired factor labels.

Upvotes: 3

Views: 1913

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174813

The A fix is to add a numeric version of z, not to convert it

hline.data <- data.frame(z = factor(c("a", "b", "c", "d")), vs = c(0,0,1,1), 
                         am = c(0,1,0,1))

## add numeric version of `z` as a new variable 
hline.data <- transform(hline.data, z0 = as.numeric(z))

p <- qplot(mpg, factor(sample(c("a", "b", "c", "d"), nrow(mtcars), T)), 
           data=mtcars, facets = vs ~ am)
p + geom_hline(aes(yintercept = z0), hline.data)

Producing

enter image description here

Upvotes: 4

Related Questions