Reputation: 429
I have a bit of a coding issue. I have a MWE below:
df <- data.frame(year=seq(1961,2013,1), group1=rnorm(53), group2=rnorm(53))
p <- ggplot(df, aes(x=year)) +
geom_line(aes(y=group1, linetype="group1")) +
geom_line(aes(y=group2, linetype="group2"))
p1 <- ggplot(df, aes(x=year)) +
geom_line(aes(y=group1, linetype="group1"), lwd=1.5) +
geom_line(aes(y=group2, linetype="group2"))
p
produces a very standard looking graph with no issues:
However, when I try to change the linewidth in p1
, of one of the geom_line
, this distorts the legend as such:
The dotted aspect of the line remains the same but the lined segment is being affected by the lwd=1.5
from the first line.
Is there an error/shortcoming in my approach to this problem or a larger issue at play here?
Upvotes: 1
Views: 346
Reputation: 125478
If you want a nice legend with different linetypes and linewidths then you should convert your data to long format, map group
on both linetype
and lwd
aestehtics and set the lwd
manually using scale_size_manual
.
library(ggplot2)
library(dplyr)
library(tidyr)
df <- data.frame(year=seq(1961,2013,1), group1=rnorm(53), group2=rnorm(53))
df %>%
pivot_longer(-year, names_to = "group") %>%
ggplot(aes(x=year)) +
geom_line(aes(y=value, linetype = group, lwd = group)) +
scale_size_manual(values = c(1.5, .5))
Created on 2020-05-27 by the reprex package (v0.3.0)
Upvotes: 1