繁体   English   中英

在多面网格ggplot2中插入一个额外的图

[英]Inserting an extra plot into faceted grid, ggplot2

我想以ggplot2多面图格式显示一组参数。 其中三个参数来自同一数据集,并且可以轻松实现。 我现在想在网格中添加第四个图,该图的数据集与其他数据集的长度/值完全不同(但仍然可以一起查看)。

这是我最好的(糟糕)。 有没有一种方法可以完全对齐坐标和主题? 谢谢

library(ggplot2)

data(mtcars)
data(iris)

a_plot <- ggplot(mtcars, aes(mpg, disp))+
  geom_line()+
  facet_wrap(~cyl,nrow=2,scales='free')+
  theme_bw()

b_plot<- ggplot(iris, aes(Sepal.Length,Petal.Length))+
  geom_line()+
  ggtitle('imposter')+
  theme_bw()

vp <- viewport(width = 0.52, height = 0.5, x = 0.75, y = 0.25)

png("test.png")
print(a_plot)
print(b_plot, vp = vp)
dev.off()][1]][1]

在此处输入图片说明

一种建议是在数据中处理此问题,并使图面自然地工作。 (我在这里使用dplyr来合并数据集,但这只是为了方便。任何提供一组要绘制的列的机制都应该起作用。)

library(dplyr)
library(ggplot2)

bind_rows(
  transmute(mtcars, x=mpg         , y=disp        , z=as.character(cyl)),
  transmute(iris,   x=Sepal.Length, y=Petal.Length, z="imposter")
) %>%
  ggplot(aes(x, y)) +
  geom_line() +
  facet_wrap(~ z, nrow = 2, scales = "free") +
  theme_bw()

mtcars和虹膜的多面组合

在它们中使用参数plot.marginpanel.spacing自定义要绘制的背景的大小。 然后将视口修改为宽度,使其与您的其他3个图匹配。 您可能需要尝试一些时间,但这是可以实现的。

library(ggplot2)
library(grid)

a_plot <- ggplot(mtcars, aes(mpg, disp))+
  geom_line()+
  facet_wrap(~cyl,nrow=2,scales='free')+
  theme_bw()+
  theme(plot.margin = unit(c(0,0.3,0,0), "cm"),
        panel.spacing= unit(1, "cm"))


b_plot<- ggplot(mtcars, aes(mpg,disp))+
  geom_line()+
  ggtitle('imposter')+
  theme_bw()

vp <- viewport(width = 0.49, height = 0.5, x = 0.75, y = 0.25)
print(a_plot)
print(b_plot, vp = vp)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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