I would like to display a set of parameters in the ggplot2
faceted plot format. 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.)
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()