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"))
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"))
One option is to use an interior fill for each element. There may be a way to use override.aes
to get the points to be a point in the legend, but I wasn't able to get that with any quick experimentation.
p <- df %>%
ggplot(aes(x1)) +
geom_ribbon(aes(ymin = y, ymax = z, fill = "area")) +
geom_point(aes(y = jj, fill = "points1"), shape=21, colour="blue") +
geom_point(aes(y = hh, fill = "points2"), shape=21, colour="purple") +
scale_x_continuous(breaks = some_names %>% select(x1) %>% unlist %>% unname,
labels = some_names %>% select(x) %>% unlist %>% unname ) +
scale_fill_manual(name = "legend",
values = c("area" = "red","points1" = "blue","points2" = "purple"),
guide = guide_legend(override.aes=aes(colour=NA)))
p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With