ggplot2:单个图例中的多个图 [英] ggplot2: multiple plots in a single row with a single legend

查看:1100
本文介绍了ggplot2:单个图例中的多个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 图书馆(ggplot2)
图书馆(网格)
库(gridExtra)
dsamp< - 菱形[sample(nrow(diamonds),1000),]
p1 < - qplot(price,carat,data = dsamp,颜色=净度)
p2 <-qplot(价格,深度,数据= dsamp,颜色=净度)
g < - ggplotGrob(p1 + theme(legend.position =bottom))$ grobs
legend< -g [[which(sapply(g,function(x)x $ name)==guide-box)]]
grid.arrange(arrangeGrob(p1 + theme (3 / 7,3 / 7,1 / 7)))

然而,

然而,我不想猜测图表和图例的宽度(并指定 ncol ),但将其从 p1 p2



这个任务离子是相似的


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

library(ggplot2) 
library(grid)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]    
p1 <- qplot(price, carat, data=dsamp, colour=clarity)
p2 <- qplot(price, depth, data=dsamp, colour=clarity)
g <- ggplotGrob(p1 + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
grid.arrange(arrangeGrob(p1+theme(legend.position="right"),p2+theme(legend.position="none"),legend,ncol=3,widths=c(3/7,3/7,1/7)))

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 <- function(...) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lwidth <- sum(legend$width)
  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:

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 <- melt(dsamp, id.vars = c("price", "clarity"), measure.vars = c("carat", "depth"))
ggplot(dmelt, aes(x = price, y = value, color = clarity)) +
  geom_point() +
  facet_wrap(~ variable, scales = "free")

这篇关于ggplot2:单个图例中的多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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