ggplot2:合并两个图例

Luc*_*nno 4 r legend ggplot2

我试图用 ggplot2 用两组不同的点绘制一个区域,但我总是得到两个不同的图例。我读过这个这个, 但我仍然有两个传说。下面是代码和图表。
非常感谢

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")) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

luk*_*keA 5

你可以做点什么

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"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

或者

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"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明