3
votes

Take the following example:

library(ggplot2)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]

ggplot(dsamp, aes(x = x)) +
    geom_line(aes(y = y, linetype = "Simple Model")) +
    geom_line(aes(y = z, linetype = "Complex Model"))

Which produces this graph: enter image description here

Ok. My problem is I want the linetypes reversed. I want the simple model to have the solid line and the complex model to be dashed. By default, the alphabetical order seems to be deciding the linetype here. I have tried different variations using scale_linetype_manual etc, but try as I might I cannot get the simple line to be solid and the complex to be dashed and at the same time keep the 'simple' & 'complex' titles in the legend. Before someone suggests it I am trying to avoid melting/reshaping this data such that both y variables are in 1 column, because the real data has more in the plot etc and it would be really complex.

Edit: Ok thanks to Haboryme for his reply. I have found the source of my confusion.

Take the following plot:

ggplot(dsamp, aes(x = x)) +
    geom_line(aes(y = y, linetype = "Simple Model"), size = 1.5) +
    geom_line(aes(y = z, linetype = "Complex Model"), size = 1.5) +
    scale_linetype_manual(values=c( 5, 1))

The legend appears to show linetype both as solid lines: enter image description here

However if I change it to linetype 3:

ggplot(dsamp, aes(x = x)) +
    geom_line(aes(y = y, linetype = "Simple Model"), size = 1.5) +
    geom_line(aes(y = z, linetype = "Complex Model"), size = 1.5) +
    scale_linetype_manual(values = c( 3, 1))

The linetype legend is correct: enter image description here

Well I guess this solves my problem - I will simply have to use linetype 3. It seems linetype 5 with size 1.5 just doesn't fit in the legend space well ?

1
I get the desired output with +scale_linetype_manual(values=c(2,1))Haboryme
oooo ok you are right. Ok something weird happens in my real data. So I am using linetype 5 where you have used 2. In my real data the legend for linetype 5 appears as a solid line instead of dashed. If I use linetype 2 it works as above. Ok looking back it is coming from something I've done in theme options I thinkuser2498193
you can change line-size only in legend by + guides(linetype = guide_legend(override.aes = list(size = 0.5)))cuttlefish44

1 Answers

5
votes
ggplot(dsamp, aes(x=x)) +
  geom_line(aes(y=y, linetype="Simple Model"),size=1.5) +
  geom_line(aes(y=z, linetype="Complex Model"),size=1.5)+
  scale_linetype_manual(values=c(5,1))

The above code will give you a plot where both lines look similar in the legend.
This is because linetype=5 is equivalent to "longdash" (2 is "dashed"). The longdashes are too long to show in the legend.

If you want to retain the size=1.5 (or higher) with the longdashes and have a proper legend you will need to also change the size of the legend, for example with:

+theme(legend.key.size=unit(2,"cm"))