user2498193 - 14 days ago 6

R Question

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:

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:

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:

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 ?

Answer

```
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"))
```