Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: how to create correct legend after using scale_xx_manual

Tags:

r

ggplot2

I have a plot with three different lines. I want one of those lines to have points on as well. I also want the two lines without points to be thicker than the one without points. I have managed to get the plot I want, but I the legend isn't keeping up.

library(ggplot2)

y <- c(1:10, 2:11, 3:12)
x <- c(1:10, 1:10, 1:10)
testnames <- c(rep('mod1', 10), rep('mod2', 10), rep('meas', 10))
df <- data.frame(testnames, y, x)

ggplot(data=df, aes(x=x, y=y, colour=testnames)) +
   geom_line(aes(size=testnames)) +
   scale_size_manual("", values=c(0.5,1,1)) +
   geom_point(aes(alpha=testnames), size=5, shape=4) +
   scale_alpha_manual("", values=c(1, 0, 0))

enter image description here

I can remove the second (black) legend:

ggplot(data = df, aes(x=x, y=y, colour=testnames)) +
   geom_line(aes(size=testnames)) +
   scale_size_manual("", values=c(0.5,1,1), guide='none') +
   geom_point(aes(alpha=testnames), size=5, shape=4) +
   scale_alpha_manual("", values=c(1, 0.05, 0.05), guide='none')

enter image description here

But what I really want is a merge of the two legends - a legend with colours, cross only on the first variable (meas) and the lines of mod1 and mod2 thicker than the first line. I have tried guide and override, but with little luck.

like image 220
Riinu Pius Avatar asked Mar 15 '23 09:03

Riinu Pius


1 Answers

You don't need transparency to hide the shapes for mod1 and mod2. You can omit these points from the plot and legend by setting their shape to NA in scale_shape_manual:

ggplot(data = df, aes(x = x, y = y, colour = testnames, size = testnames)) +
  geom_line() +
  geom_point(aes(shape = testnames), size = 5) +
  scale_size_manual(values=c(0.5, 2, 2)) +
  scale_shape_manual(values=c(8, NA, NA)) 

This gives the following plot:

enter image description here


NOTE: I used some more distinct values in the size-scale and another shape in order to better illustrate the effect.

like image 90
Jaap Avatar answered Apr 05 '23 22:04

Jaap