3

I made a scatter plot and then added a regression line. I'm new in ggplot2 and I didn't understand so well how to add a legend. I want a circle like the scater plot saying "data", and a line saying "regression". How can I do this?

library(ggplot2)

ggplot(mpg, aes(displ, cty)) + geom_point(shape = 1) +
  stat_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
  theme_classic() + theme(panel.border = element_rect(colour = "black", fill=NA),
                          aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12))

enter image description here

And I want something like:

enter image description here

Daniel Valencia C.
  • 2,159
  • 2
  • 19
  • 38

1 Answers1

2

Custom legends can be tricky to achieve in ggplot as the system is heavily based around "mapping" your data to a scale and then using that to create the legend. For custom legends, you can use an aes() call that manually sets the label you want in the legend, like:

ggplot(mpg, aes(displ, cty)) + 
    geom_point(aes(shape = "Data")) +
    stat_smooth(aes(linetype = "Regression"), method = "lm", 
                formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
    scale_shape_manual(values = 1) +
    labs(shape = "", linetype = "") +
    theme_classic() + 
    theme(panel.border = element_rect(colour = "black", fill=NA),
          aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12))
Marius
  • 58,213
  • 16
  • 107
  • 105