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

2

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.