ggplot2: merge two legends

ggplot2, legend, r

Solution

You could do something in the veins of

library(tidyverse)
packageVersion("ggplot2")
# [1] ‘2.2.1’
df %>% 
  gather(var, val, jj, hh) %>% 
  ggplot(aes(x1, val, ymin=y, ymax=z, color=var, fill=var)) + 
  geom_ribbon(color=NA) + 
  geom_point() + 
  scale_color_manual(values=c("blue","purple"), name="leg", labels = c("lab1","lab2")) + 
  scale_fill_manual(values = rep("red", 2), name="leg", labels= c("lab1","lab2"))

or

library(tidyverse)
df %>% 
  gather(var, val, jj, hh) %>% 
  bind_rows(data.frame(x=NA,y=NA,z=NA,x1=NA,var="_dummy",val=NA)) %>% 
  ggplot(aes(x1, val, ymin=y, ymax=z, color=var, fill=var)) + 
  geom_ribbon(color=NA) + 
  geom_ribbon(color=NA, fill="red") + 
  geom_point() + 
  scale_color_manual(
    values=c("#FFFFFF00", "blue","purple"), name="leg", labels = c("lab1","lab2","lab3")) + 
  scale_fill_manual(
    values = c("red", rep(NA, 2)), name="leg", labels= c("lab1","lab2","lab3"))

Problem

I'm trying to plot an area with two different set of points with ggplot2 but I get always two different legends. I've read this and this but I still have two legends. Below the code and the chart. Thank you very much ``` library(ggplot2) library(dplyr) set.seed(1) df <- data.frame(x = letters, y = 1:26 +runif(26), z = 2*(1:26) + runif(26), jj = 1:26, hh = 1:26*2, x1 = 1:26) some_names <- df %>% filter(row_number() %% 10 == 1) %>% select(x,x1) p <- df %>% ggplot(aes(x1)) + geom_ribbon(aes(ymin = y, ymax = z, fill = "area")) + geom_point(aes(y = jj, colour = "points1")) + geom_point(aes(y = hh, colour = "points2")) + scale_x_continuous(breaks = some_names %>% select(x1) %>% unlist %>% unname, labels = some_names %>% select(x) %>% unlist %>% unname ) p + scale_fill_manual(name = "legend", values = c("area" = "red","points1" = NA,"points2" = NA)) + scale_colour_manual(name = "legend", values = c("area" = NA ,"points1" = "blue","points2" = "purple")) ```

Original source

Related problems