/ / linea orizzontale; asse y come fattore: ggplot2 - r, ggplot2

linea orizzontale; asse y come fattore: ggplot2 - r, ggplot2

Se ho un fattore per la mia variabile y e provo a usare geom_hline in facet_grid Ottengo un errore:

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

Perché ricevo l'errore e come posso ripararlo?

PS Posso risolverlo trasformandolo in numerico come 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)

Ma perdo le etichette dei fattori desiderate.

risposte:

2 per risposta № 1

Il Una correzione è aggiungere una versione numerica di z, non per convertirlo

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)

Produrre

inserisci la descrizione dell'immagine qui