使用拼凑法将ggplot2中的图例合并和合并 [英] Combine and merge legends in ggplot2 with patchwork

查看:178
本文介绍了使用拼凑法将ggplot2中的图例合并和合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将两个或多个情节合并起来,合并他们的传说.

例如,我可以创建一些数据和两个方案,如下所示.

 #个软件包库(ggplot2)图书馆(拼凑而成)#第一情节set.seed(07042020)x<-符文(50)y<-符(50)data1<-data.frame(x = x,y = y,z = runif(50,0,2))p1<-ggplot(data1)+ geom_point(aes(x,y,col = z))1 

  data2<-data.frame(x = x,y = y,z = runif(50,-1,1))p2<-ggplot(data2)+ geom_point(aes(x,y,col = z))2 

以下代码是我到目前为止尝试过的内容,但这不是预期的结果.我想用一个图例合并两个图,即创建一个唯一且通用的图例"z",以使两个图的点根据该通用图例着色.这可能吗?

 <代码> p1 + p2 + plot_layout(guides ="collect") 

唯一的缺点是您可能必须手动指定限制,因为 p1 中的比例不知道 p2 中的值.

I would like to combine two or more plots merging their legends.

For example, I can create some data and two scenarios as follows.

# packages
library(ggplot2)
library(patchwork)

# first plot
set.seed(07042020)
x <- runif(50)
y <- runif(50)
data1 <- data.frame(x = x, y = y, z = runif(50, 0, 2))
p1 <- ggplot(data1) + geom_point(aes(x, y, col = z))
p1

data2 <- data.frame(x = x, y = y, z = runif(50, -1, 1))
p2 <- ggplot(data2) + geom_point(aes(x, y, col = z))
p2

The following code is what I tried so far but it's not the intended result. I would like to merge the two plots with a single legend, i.e. create a unique and common legend "z" in such a way that the points of the two plots are coloured according to this common legend. Is this possible?

p1 + p2 + plot_layout(guides = "collect")

Created on 2020-04-07 by the reprex package (v0.3.0)

解决方案

I think two legends can only be combined when they have the exact same properties, i.e. share limits, labels, breaks etc. You can provide a common legend by sharing a common scale, one way to do that in patchwork is to use the & operator, which sort of means 'apply this to all previous plots':

p1 + p2 + plot_layout(guides = "collect") & 
  scale_colour_continuous(limits = range(c(data1$z, data2$z)))

Only downside is that you'd probably manually have to specify the limits as the scale in p1 does not know about the values in p2.

这篇关于使用拼凑法将ggplot2中的图例合并和合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆