Reputation: 729
I want to generate a plot that specifies that line 1 is a linear trend with a solid line and line 2 is a horizontal line with longdash line. Following tips here and elsewhere, I use scale_linetype_manual()
to specify the linetypes after mapping them in geoms.
Consider:
library(dplyr)
library(ggplot2)
p <- ggplot(
data = mutate(mtcars, limit = 20),
mapping = aes(x = hp, y = mpg)
) +
theme_bw() +
geom_point(color = "purple") +
geom_smooth(
aes(linetype = "linear trend"),
method = "lm",
formula = "y ~ x",
se = FALSE,
color = "black", # col = "dark green",
size = 1
) +
#Add precision cut-off
geom_hline(
mapping = aes(yintercept = limit, linetype = "cut-off"),
color = "black", #color = "dark green",
alpha = 0.5,
size = 1,
na.rm = TRUE
) +
scale_linetype_manual(
name = NULL,
values = c(
"longdash", #cut-off
"solid" #mean
))
p
The resulting legend in the plot shows both lines are "solid", but the cut-off is clearly a different linetype ("long-dash") in the plot (and in the code). Is there a way for the legend to reflect what the plot shows? Thanks.
Upvotes: 0
Views: 392
Reputation: 635
You can make the legend key a little wider so you can see the full length of the dash (i.e, use r theme(legend.key.width = unit(1.25, units = "cm"))
).
ggplot(
data = mutate(mtcars, limit = 20),
mapping = aes(x = hp, y = mpg)
) +
theme_bw() +
geom_point(color = "purple") +
geom_smooth(
aes(linetype = "linear trend"),
method = "lm",
formula = "y ~ x",
se = FALSE,
color = "black", # col = "dark green",
size = 1
) +
#Add precision cut-off
geom_hline(
mapping = aes(yintercept = limit, linetype = "cut-off", alpha="cut-off"),
color = "black", #color = "dark green",
alpha = 0.5,
size = 1,
na.rm = TRUE
) +
scale_linetype_manual(
name = NULL,
values = c(
"longdash", #cut-off
"solid" #mean
)) +
theme(legend.key.width = unit(1.25, units = "cm"))
Upvotes: 1