1
votes

I have a scatterplot where I want 4 guide lines. I have not used variables from the dataset directly to defines those lines in the plot script. (The vertical lines is mean and median of the x-values. And the slopes of the two other lines are 1 and 0.5.)
How can I define colours for the lines and get correct legend labels? In my plot the colours and labels are mixed up.

The question answered here (possibly duplicate) is similar to my question above, but not completely, I think. The former question is about difference between scale_colour - and scale_fill_manual and the importance to include aes() to get a legend, I think. My question is about mixing of legend-labels and colours since I had not defined the values in the geom_- call and had separated the values and colours in the scale_colour_manual().

My code:

library(dplyr)
df <- iris %>%
  group_by(Species) %>%
  do({
    mod = lm(Sepal.Length~Petal.Length, data = .)
    data.frame(Intercept = coef(mod)[1],
               Slope = coef(mod)[2],
               SD= summary(mod)$coefficients[2,2])
  })

meanSlope <- mean(df$Slope)
medianSlope <- median(df$Slope)

library(ggplot2)
ggplot(data=df, aes(x=Slope, y=SD)) +
  geom_point() +
  scale_x_continuous(limits = c(0,1.0)) +
  scale_y_continuous(limits = c(0,1.0))+
  geom_abline(aes(intercept = 0, slope = 1, colour="red"), show.legend = TRUE) +
  geom_abline(aes(intercept = 0, slope = 0.5, colour="blue"), show.legend = TRUE) +
  geom_vline(aes(xintercept = meanSlope, colour= "green"), show.legend = TRUE) +
  geom_vline(aes(xintercept= medianSlope, colour= "darkgreen"), show.legend = TRUE) +
  scale_colour_manual(name="Guide lines", values=c("red", "blue", "green", "darkgreen"), 
                      labels=c("1 SD", "0.5 SD", "mean", "median")) 

enter image description here

1

1 Answers

3
votes

Try mapping to the name of the line, then setting colors afterwards:

ggplot(data=df, aes(x=Slope, y=SD)) +
  geom_point() +
  scale_x_continuous(limits = c(0, 1.0)) +
  scale_y_continuous(limits = c(0, 1.0))+
  geom_abline(aes(intercept = 0, slope = 1, colour = "1 SD"), show.legend = TRUE) +
  geom_abline(aes(intercept = 0, slope = 0.5, colour = "0.5 SD"), show.legend = TRUE) +
  geom_vline(aes(xintercept = meanSlope, colour = "mean"), show.legend = TRUE) +
  geom_vline(aes(xintercept= medianSlope, colour = "median"), show.legend = TRUE) +
  scale_colour_manual(name = "Guide lines", 
                      values = c('1 SD' = "red", '0.5 SD' = "blue", 
                                 mean = "green", median = "darkgreen")) 

enter image description here