1

I'm smoothing out data points using rms::rcs() and geom_smooth() with different levels of smoothness as additional layers. I'd like to add a custom legend to the side that identifies each smoothness parameter, but I'm not sure exactly how to do this. I've tried this stackoverflow post: R: Custom Legend for Multiple Layer ggplot with no luck.

How would I add a custom legend for each geom_smooth() using linetype?

Edit: I've updated the question to reflect a question around linetype and not color.

Sample Code:

library(rms)
  p1 <- ggplot(diamonds, aes(carat, price)) + 
  geom_smooth(method = "gam", formula = y ~ rms::rcs(x, 3), aes(linetype = "solid")) + 
  geom_smooth(method = "gam", formula = y ~ rms::rcs(x, 4), aes(linetype = "dashed")) + 
  geom_smooth(method = "gam", formula = y ~ rms::rcs(x, 5), aes(linetype = "dotdash")) +
  scale_colour_manual(name="Knots", values=c("solid", "dashed", "dotdash"), labels = c("3", "4", "5"))

Plot:

enter image description here

Vedda
  • 7,066
  • 6
  • 42
  • 77
  • 2
    within each `geom_smooth` call, use `aes(color = X)`. e.g. `geom_smooth(method = "gam", formula = y ~ rms::rcs(x, 3), aes(color = "blue"))` – bouncyball Jun 06 '17 at 21:11
  • @bouncyball Thanks! Does the same apply if I wanted to use `linetype` also? – Vedda Jun 06 '17 at 21:14
  • 2
    indeed it should – bouncyball Jun 06 '17 at 21:16
  • @bouncyball This is what I tried, but not working: `p1 <- ggplot(diamonds, aes(carat, price)) + geom_smooth(method = "gam", formula = y ~ rms::rcs(x, 3), aes(linetype = "solid")) + geom_smooth(method = "gam", formula = y ~ rms::rcs(x, 4), aes(linetype = "dashed")) + geom_smooth(method = "gam", formula = y ~ rms::rcs(x, 5), aes(linetype = "dotdash")) + scale_colour_manual(name="Knots", values=c("solid", "dashed", "dotdash"), labels = c("3", "4", "5"))` – Vedda Jun 06 '17 at 21:22
  • @Henrik I've updated question to reflect a new question using `linetype` instead of `color` since the duplicate link doesn't work with `linetype` – Vedda Jun 06 '17 at 21:30
  • 1
    @Henrik nvm, `scale_linetype_manual()` is the appropriate method. Thanks! – Vedda Jun 06 '17 at 22:32

0 Answers0