Missing legend items when using common.legend in ggarrange with ggplot2

Viewed 1360

Given a setup like:

require(ggplot2)
require(ggpubr)

size = 20
s = 0.2
d = seq(0,2*pi, length.out=size)
df = data.frame(
  d=d + runif(size)*s,
  a=sin(d) + runif(size)*s,
  b=sin(d-10) + runif(size)*s,
  c=cos(2*d) + runif(size)*s
)

when trying to plot the lines with ggarrange

ggarrange(
  (
    ggplot(df, aes(x=d, palette="Set1"))
    + geom_smooth(aes(y=a, color="A"), se=FALSE)
    + scale_color_manual(values=c("#999999"))
  ),
  (
    ggplot(df, aes(x=d, palette="Set2"))
    + geom_smooth(aes(y=b, color="B"), se=FALSE)
    + geom_smooth(aes(y=c, color="C"), se=FALSE)
  ),
  common.legend=TRUE
)

the common legend only shows the items from the first ggplot argument, in this case the A line. How can I get a common legend to include all of the lines without reformatting the dataframe and using facet?

ggarrange line plots

1 Answers

You can do this by defining the limits in scale_color_manual() in the first plot, along with setting a value for each of your values.

For example, you could add

 scale_color_manual(limits = c("A", "B", "C"),
                             values = c("#999999",hcl(c(15, 195), 100, 65)))

to the first plot of your example.

ggarrange(
    (
        ggplot(df, aes(x=d, palette="Set1"))
        + geom_smooth(aes(y=a, color="A"), se=FALSE)
        + scale_color_manual(limits = c("A", "B", "C"),
                             values = c("#999999",hcl(c(15, 195), 100, 65)))
    ),
    (
        ggplot(df, aes(x=d, palette="Set2"))
        + geom_smooth(aes(y=b, color="B"), se=FALSE)
        + geom_smooth(aes(y=c, color="C"), se=FALSE)
    ),
    common.legend=TRUE
)

enter image description here

Related