2
votes

I am trying to generate legends for geom_smooth and geom_abline using the following code

ggplot(data = d, aes(x = log(x), y =log(y) )) +
  geom_hex() +
  geom_smooth(method='lm',formula=y~x, color = "red", show.legend=TRUE) +
  geom_abline(color = "green", show.legend=TRUE) +
  scale_colour_manual(name='Lines', values=c("Regression", "Abline"))+
  theme_bw() 

I have seen a related question here: ggplot2 legend for abline and stat_smooth, but none of the recommended solutions generate a legend. Any ideas?

Some fake data:

x <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
y <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
d <- data.frame(x = x, y = y)

EDIT: Following Camile's suggestion, I added aes() wrapping around the colors, but to no avail.

ggplot(data = d, aes(x = log(x), y =log(y) )) +
  geom_hex() +
  geom_smooth(method='lm',formula=y~x, aes(color = "red"), show.legend=TRUE) +
  geom_abline(aes(color = "green"), show.legend=TRUE) +
  scale_colour_manual(name='Lines', values=c("Regression", "Abline"))+
  theme_bw() 

This works for the geom_smooth line, but now geom_abline is saying: "Error: geom_abline requires the following missing aesthetics: slope, intercept"

1
You haven't assigned anything to color in your aes. Even if it's just a dummy assignment, there has to be something inside an aescamille
What you give as values to scale_color_manual should be names or hex codes of colors, not the names of groups. Also, geom_abline requires a slope and intercept, which you haven't setcamille

1 Answers

2
votes

Here is an option

ggplot(data = d, aes(x = log(x), y =log(y) )) +
  geom_hex() +
  geom_smooth(method='lm',formula=y~x, aes(color = "red")) +
  geom_abline(aes(slope = 1, intercept = 0, color = "green"), show.legend=FALSE) +
  scale_colour_manual(name='Lines',
                      labels = c("Abline", "Regression"), 
                      values=c("green", "red")) +
  theme_bw()

When we map color to "green" inside geom_abline ggplot complained

error: geom_abline requires the following missing aesthetics: slope, intercept

That's why I had to include these aesthetics too.

enter image description here