John Palowitch
John Palowitch

Reputation: 307

Craft custom, separate legend for geom_abline

I realize there are many similarly-titled queries out there, but I have looked through many and none seem to solve my particular problem. Happy to be wrong on this, though.

Here's some code and the plot it makes:

library(ggplot2)
set.seed(12345)
types <- c("a", "b")[sample(rep(1:2, each = 5))]
Data <- data.frame(x = rnorm(10), 
                   y = rnorm(10), 
                   Type = types)

p1 <- ggplot(Data, aes(x = x, y = y)) + 
  geom_point(aes(colour = Type), size = 2.5) +
  geom_abline(aes(slope = 0, intercept = 1, colour = "A cool line"), lty = "dotted", lwd = 1.5) + 
  geom_line(aes(colour = Type), lwd = 1.5) + 
  ggtitle("abline legend plz") 

plot generated from the sample code

This is an ok plot, but I need a few things to change:

  1. No linetype indicators in the legend boxes (also, whhyy are the a/b legend lines displaying the "dotted" linetype?)
  2. I would like the legend for "A cool line" to appear separately, in a new legend, but in the same format as the other legend
  3. Bonus points: no point-type indicators in any of the legend boxes.

Here's an MS paint rendering of the legend column of my dreams:

enter image description here

Some notes:

Upvotes: 2

Views: 626

Answers (1)

Constantinos
Constantinos

Reputation: 1327

If your horizontal dotted line is always horizontal, I'd use:

p1 <- ggplot(Data, aes(x = x, y = y)) + 
          geom_point(aes(colour = Type), size = 2.5) +
          geom_line(aes(colour = Type), lwd = 1.5) + 
          geom_hline(aes(yintercept = 1, linetype = "A cool line"), colour = "darkgreen", lwd = 1.5) + 
          scale_colour_discrete(name = "Type") +
          scale_linetype_manual(name = "A cool (custom) title", 
                                values = c("A cool line" = "dotted")) + 
          ggtitle("abline legend plz")  + 
          guides(colour   = guide_legend(override.aes = list(shape = NA)),
                 linetype = guide_legend(override.aes = list(linetype = "solid")))

This forces the dark green line in the legend to be horizontal. Here's the result: enter image description here

If however you want to use geom_abline() because your dotted line might have a slope, you'd replace the

geom_hline(aes(yintercept = 1, linetype = "A cool line"), colour = "darkgreen", lwd = 1.5) +

part with

geom_abline(aes(slope = 0, intercept = 1, linetype = "A cool line"), colour = "darkgreen", lwd = 1.5) + 

which however would replace the the dark green line in the legend with a sloped line. Nice question, by the way!

Upvotes: 3

Related Questions