简体   繁体   中英

How to add legend to combined ggplot2 (different values)

I need to add a legend to my combined ggplot but don't seem to succeed. The data is made up from three different values of which "targeted" and "non targeted" are in one plot and "response" in the other. I would like to add the legend at the bottom of the combined plot. Thanks in advance

Output of my current code1

A <- ggplot(placeholder) + 
  geom_line(aes(x=date, y= targeted), color='#0072b2', group= 1, size=1.25) + 
  geom_line(aes(x=date, y= non_targeted), color='#d55e00' , group= 1, size=1.25) +
  theme(axis.text.x = element_text(angle = 90)) +
  labs(y= "Y1", x = "Date") + theme_classic() +
  theme(axis.text.x = element_text(angle = 90))


A 

B <- ggplot(media_analysis) + 
  geom_line(aes(x=date, y= nuisance_reports), color='#f0e442', group= 1, size=1.25) +
  theme(axis.text.x = element_text(angle = 90)) +
  labs(y= "Y2", x = "Date") + theme_classic() +
  theme(axis.text.x = element_text(angle = 90))

B 

combined <- plot_grid(A, B, 
                      labels = c("A", "B"),
                      ncol = 2, nrow = 1)  
combined

Easiest is to use facets. This requires minor data wrangling (see comments).

suppressMessages(library(tidyverse))

set.seed(42)
foo <- cbind(data.frame(replicate(3, rnorm(30))), date = ISOdate(1,1,1:30))

# make a data frame which has all the values in one column, 
# and all the dates in another
# there needs to be a facetting variable

foo %>% 
  pivot_longer(starts_with("X")) %>%
  ## combine X1 and X2 to one category
  mutate(new_name = ifelse(grepl("X[1-2]", name), "A", "B")) %>%
  ## now facet by this new variable
  ggplot() +
  geom_line(aes(date, value, color = name)) +
  facet_wrap(~new_name) +
  ## place at bottom
  theme(legend.position = "bottom")

or combining the plots with patchwork

This will require same name and limits of the guides

library(patchwork)
p1 <-  
  foo %>% 
  pivot_longer(matches("X[1-2]")) %>%
  ggplot() +
  geom_line(aes(date, value, color = name)) +
  ## now define the same names for your color legend and get the same limits
  scale_color_brewer("color", limits = paste0("X", 1:3))

p2 <-  foo %>% 
  ggplot() +
  geom_line(aes(date, X3, color = "X3")) +
  scale_color_brewer("color", limits = paste0("X", 1:3))

p1 + p2 +
  ## combine the legends 
  plot_layout(guides = "collect") +
  # add tags 
  plot_annotation(tag_levels = "A") &
  ## place at bottom
  theme(legend.position = "bottom")

Created on 2022-06-29 by the reprex package (v2.0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM