3

Is it possible to have different sized (i.e. thick) lines drawn with geom_line?

The size parameters is the same for all lines, irrespective of the group:

bp <- ggplot(data=diamonds, aes(x=cut, y=depth)) +
  geom_line(aes(color=cut), size=1)

However, I want the thickness of the lines to reflect their relative importance measured as number of observations:

relative_size <- table(diamonds$cut)/nrow(diamonds)
bp <- ggplot(data=diamonds, aes(x=cut, y=depth)) +
  geom_line(aes(color=cut), size=cut)
bp
# Error: Incompatible lengths for set aesthetics: size

Interestingly, geom_line(..., size=cut) works but not as expected, since it doesn't alter line size at all.

MERose
  • 4,048
  • 7
  • 53
  • 79
  • 3
    You could put `size=....` inside the `aes`. – Heroka Sep 28 '15 at 13:08
  • @Heroka, do you want to provide an answer such that I can accept it? – MERose Sep 28 '15 at 13:32
  • @MERose LyzandeR already provided an answer, you can accept that one. – Paul Hiemstra Sep 28 '15 at 13:33
  • That's not the same and much more complicated. – MERose Sep 28 '15 at 13:37
  • Well, @LyzandeR gave an answer that's exactly as you asked ("thickness to reflect relative importance"). My suggestion does not warrant a standalone answer anyway. – Heroka Sep 28 '15 at 14:14
  • Thanks @Heroka very kind of you :). @MERose, you need to be careful when you use a variable that is categorical as a size measure. If `cut` were a character field the graph would look problematic. It makes sense (at least to me) when you want the relative difference to be depicted as size to provide a numeric field so that the relative difference can be calculated. Providing a factor (as in this occasion) works well because factors are integers internally. – LyzandeR Sep 28 '15 at 14:38

1 Answers1

5

In order to do this you need to create a new variable for relative_size that will be of the same length as the rows of the data.frame and add it to your data.frame. In order to do this, you could do:

#convert relative_size to a data.frame
diams <- diamonds
relative_size <- as.data.frame(table(diamonds$cut)/nrow(diamonds))

#merge it to the diams data.frame so that it has the same length
diams <- merge(diams, relative_size, by.x='cut', by.y='Var1', all.x=TRUE)

Note that the above can be replaced by code using dplyr:

diamonds %>% group_by(cut) %>% mutate(size = length(cut) / nrow(diamonds))

Then you need to follow @Heroka 's advice and use size inside of aes with your newly created column in your diams data.frame:

bp <- ggplot(data=diams, aes(x=cut, y=depth)) +
  geom_line(aes(color=cut, size=Freq))
bp

And it works:

enter image description here

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
LyzandeR
  • 37,047
  • 12
  • 77
  • 87