[英]How to add legend to combined ggplot2 (different values)
我需要在我的组合 ggplot 中添加一个图例,但似乎没有成功。 数据由三个不同的值组成,其中“目标”和“非目标”在一个图中,“响应”在另一个图中。 我想在组合图的底部添加图例。 提前致谢
我当前代码的输出
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
最简单的是使用分面。 这需要少量的数据争论(见评论)。
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")
或将情节与拼凑而成
这将需要指南的相同名称和限制
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")
由reprex 包于 2022-06-29 创建 (v2.0.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.