0

I am trying to add a legend to my ggplot that shows the linetype instead of differentiating by color. I've tried scale_linetype_identity and scale_linetype_manual different ways, but I'm not having any luck. I can get it to work by color, but I am trying to avoid using colors on this one. I am trying to use geom_smooth different ways to show the differences in model fit and the last step is to show the linetype in the legend, but I can't get it to work.

data

x <- c(231.5,781.8,1607.2,2698.3,4055.0,5155.6,6597.7)
y <- c(404.4,293.0,180.5,112.1,57.0,26.1,-0.4)
df <- as.data.frame(cbind(x,y))

attempted plot

ggplot(df, aes(x=x, y=y)) +
geom_point(size = 4, color = "black", fill = "white", shape = 10) +
geom_smooth(method = "lm", se = FALSE, color = "black", linetype = "solid" ) +
geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE,  color = "black", linetype 
= "dashed" ) +
geom_smooth(se = FALSE,  color = "black", linetype = "dotted" ) +
scale_linetype_identity(name = "Model fit",
                   breaks = c("solid", "dashed", "dotted"),
                   labels = c("linear", "quadratic", "loess"),
                   guide = "legend") +
ylab("Y variable") +
xlab("X variable") +
ggtitle("Differences in Model Fit by Regression Type")

Which gives me the plot below, but no legend.

scatterplot with 3 different regression line types

SportSci
  • 227
  • 3
  • 9
  • 7
    You'll need to put `linetype` inside `aes()` to get a legend. (I show an example of making legends when aesthetics are constants for `color` [here](https://aosmith.rbind.io/2018/07/19/manual-legends-ggplot2/).) – aosmith Apr 06 '20 at 14:47
  • See also https://stackoverflow.com/questions/47250975/differentiate-linetype-with-multiple-lines – Tung Apr 06 '20 at 15:58

0 Answers0