Reputation: 307
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")
This is an ok plot, but I need a few things to change:
Here's an MS paint rendering of the legend column of my dreams:
Some notes:
lwd
and size
because I need to in what I'm doing. My solution needs to allow for those to be set manually and separately.Upvotes: 2
Views: 626
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:
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