2

I am having trouble getting ggplot to display legends for colors and line types when they are only defined within an geom_abline.

I've added a very simple example below. It generates the plot as shown (no legends).

I've also tried adding a scale_color_manual to the plot, but that did not appear to do the trick. Does anybody know how to make ggplot2 display the legends?

library(ggplot2);

xy_data    = data.frame(x=runif(100, min=-0.5, max=0.5), 
                        y=runif(100, min=-0.5, max=0.5));

slope_data = data.frame(slope  = c(-1, -0.5, 0.5, 1.0),
                        model  = paste0("m", seq(1,4)),
                        robust = rep(c("Robust", "Non-robust"), 2))

merged_data = merge(xy_data, slope_data)

slope_plot = 
  ggplot()+
  geom_point(data=xy_data,     aes(x=x, y=y))+
  geom_abline(data=slope_data, aes(intercept=0, slope=slope, color=model, linetype=robust))

ggsave(plot=slope_plot, file="no_legend_slope_plot.png")

Plot: notice missing legends for color and linestyle

Roland
  • 127,288
  • 10
  • 191
  • 288
W7GVR
  • 1,990
  • 1
  • 18
  • 24

1 Answers1

3

You can try:

slope_plot = ggplot() +
  geom_point(data=xy_data, aes(x=x, y=y)) +
  geom_abline(data=slope_data, aes(intercept=0, slope=slope, color=model, linetype=robust), show_guide=TRUE)

enter image description here

Jaap
  • 81,064
  • 34
  • 182
  • 193
mucio
  • 7,014
  • 1
  • 21
  • 33
  • It works. Does anybody know why show_guide=T is NOT the default for geom_abline? It seems counterintuitive to me... – W7GVR May 01 '15 at 13:59
  • I suspect that all lines beside `geom_line` are with `show_guide = FALSE` by default, but you need someone wiser than me to know the reason behind that – mucio May 01 '15 at 14:13