[R] Multiple "scale_color_manual" statements in one plot (ggplot2, flexible legend challenge)

Jun Shen jun.shen.ut at gmail.com
Fri Jun 30 17:47:23 CEST 2017

Dear list,

I am facing an unusual situation where I need to create two sets of legends
based on the color mapping. Can't get exactly what I want and really
appreciate any advice from ggplot experts.

Let's say I have the first dataset "df1" that draws some points and based
on which a "loess" line with confidence interval is added. Then the second
dataset "df2" will produce a line and ribbon.

These are all fine. The challenge is I want to color and shape code the
points and then have two sets of legends, one for the points and one for
the lines. I have tried different ways, so far I can only get the legend
for the points but not for the lines.

Attached the sample code and sample data.

I tried to add "color" arguments to the "geom_smooth" and "geom_line" and
doesn't work. I think the problem is I need to separate the color schemes
for lines and points, but I can't use multiple scale_color_manual statement
in one ggplot.

Jun Shen

####sample data#########
df1 <-  structure(list(Y2 = c(0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L), X = c(27L, 8L,
33L, 53L, 100L, 52L, 9L, 60L, 50L, 10L, 3L, 30L, 50L, 15L, 90L,
48L, 110L, 75L, 72L, 150L, 47L, 30L), GRP = structure(c(3L, 1L,
3L, 4L, 4L, 4L, 1L, 3L, 3L, 1L, 2L, 2L, 2L, 3L, 4L, 4L, 4L, 4L,
4L, 4L, 2L, 4L), .Label = c("1", "2", "3", "4"), class = "factor")), .Names
= c("Y2",
"X", "GRP"), row.names = c(NA, -22L), class = "data.frame")

df2 <-  structure(list(X = c(1L, 10L, 20L, 30L, 40L, 50L, 60L, 70L, 80L,
90L, 100L, 110L, 120L, 130L, 140L, 150L), P025 = c(0.000319,
0.00928, 0.0232, 0.0393, 0.0556, 0.0699, 0.0833, 0.0949, 0.104,
0.113, 0.119, 0.124, 0.129, 0.134, 0.138, 0.144), P50 = c(0.00352,
0.0262, 0.0479, 0.0681, 0.0855, 0.103, 0.118, 0.134, 0.149, 0.164,
0.178, 0.19, 0.202, 0.213, 0.224, 0.234), P975 = c(0.016, 0.0523,
0.0768, 0.0987, 0.119, 0.14, 0.159, 0.178, 0.199, 0.223, 0.247,
0.269, 0.291, 0.312, 0.338, 0.36)), .Names = c("X", "P025", "P50",
"P975"), class = "data.frame", row.names = c(NA, -16L))

cols.point <- c('1'="#E69F00", '2'="#56B4E9", '3'="#009E73", '4'="#CC79A7")
shape.point <- c('1'=1, '2'=4, '3'=15, '4'=19)

ggplot(data = df1, aes(x=X)) +
  geom_point(aes(y=Y2, color=GRP, shape=GRP, size=1.5)) +
  geom_smooth(aes(y=Y2),  method= 'loess', size=1.5)  +
  geom_line(data=df2, aes(y=P50), size=1.5) +
  geom_ribbon(data=df2,aes(ymin=P025, ymax=P975), alpha=0.2) +
  theme_bw() +
  scale_color_manual(name="",values=cols.point) +
  scale_shape_manual(name="",values=shape.point) +
  guides(color = guide_legend(title='Group', override.aes=list()),
         size = 'none',
         shape = guide_legend(title='Group', override.aes=list(size=2))) +
  theme(legend.position = "top")

	[[alternative HTML version deleted]]

More information about the R-help mailing list