Pregunta

I have the following plot created from the mtcars data set and this code:

ggplot(mtcars, aes(x = mpg, y = hp, colour = factor(gear))) + geom_point() + geom_smooth(method = lm, se = FALSE)

enter image description here

I want the line size of the linear regression lines to be proportional to the number of observations in each level of factor(gear):

> count(factor(mtcars$gear))
  x freq
  3   15
  4   12
  5    5

I've tried calling size = ..count.. and ..n.., inside the main ggplot call and the geom_smooth call with no luck.

Is there a way to do this?

¿Fue útil?

Solución

Something like this should work:

library(ggplot2)
library(plyr)

line_size <- count(factor(mtcars$gear))

ggplot(mtcars, aes(x = mpg, y = hp, colour = factor(gear), size=factor(gear))) +
    geom_point(size=element_blank()) +
    geom_smooth(method = lm, se = FALSE) +
    scale_size_manual(values=line_size$freq/4)

enter image description here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top