ggplot多图叠加,ggplot2:单个图例中的多个图

I want a combined plot of two plots + their legend like this:

library(ggplot2)

library(grid)

library(gridExtra)

dsamp

p1

p2

g

legend

grid.arrange(arrangeGrob(p1+theme(legend.position="right"),p2+theme(legend.position="none"),legend,ncol=3,widths=c(3/7,3/7,1/7)))

6b1f7d7b89893143b1683c7cf58d011e.png

However I do not want to guess the width of the plots and legends (and specify ncol) but have it extracted from p1 and p2 as shown here.

So I expect I would need something like this (adapted code from the link):

grid_arrange_shared_legend_row

plots

g

legend

lwidth

grid.arrange(

do.call(arrangeGrob, lapply(plots, function(x)

x + theme(legend.position="none"))),

legend,

ncol = length(plots)+1,

widths = unit.c(rep(unit(1, "npc") - lwidth, length(plots)), lwidth))

}

grid_arrange_shared_legend_row(p1, p2)

but this is not arranging the two plots in one row but rather one column:

0a915eb9256eafe5c1b273726e075f08.png

This question is similar to this one here but different in that I am asking for the adapted widths as well. I am using code extracts both from that question + answer and the github.

解决方案

Why don't you use facetting?

library(reshape2)

dmelt

ggplot(dmelt, aes(x = price, y = value, color = clarity)) +

geom_point() +

facet_wrap(~ variable, scales = "free")

fe90d624380d92b582c77e9f841081d7.png

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值