[英]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()
在它们中使用参数plot.margin
和panel.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.