简体   繁体   English

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

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

I would like to display a set of parameters in the ggplot2 faceted plot format. 我想以ggplot2多面图格式显示一组参数。 Three of the parameters come from the same dataset and can be easily faceted. 其中三个参数来自同一数据集,并且可以轻松实现。 I'd now like to add a fourth plot into the grid, the dataset of which is a completely different length/value to the others (but still relevant to view together). 我现在想在网格中添加第四个图,该图的数据集与其他数据集的长度/值完全不同(但仍然可以一起查看)。

This is the best I have (terrible). 这是我最好的(糟糕)。 Is there a way to exactly align the coordinates and theme? 有没有一种方法可以完全对齐坐标和主题? Thank you 谢谢

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]

在此处输入图片说明

One suggestion would be to handle this in the data and let the plot faceting work naturally. 一种建议是在数据中处理此问题,并使图面自然地工作。 (I'm using dplyr here to combine the datasets, but it's only for convenience. Any mechanism that provides a single set of columns to plot on should work.) (我在这里使用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和虹膜的多面组合

Use the parameter plot.margin and panel.spacing in the them to customize the size of the background you are plotting. 在它们中使用参数plot.marginpanel.spacing自定义要绘制的背景的大小。 And then modify the viewport to width so it matches your other 3 plots. 然后将视口修改为宽度,使其与您的其他3个图匹配。 You will probably have to try some times but it is achievable. 您可能需要尝试一些时间,但这是可以实现的。

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