I'm trying to plot time series data for each "Type" in a dataset, and I want to include an inset of a zoomed in portion of the data for each plot. I can get the inset to work on each individual plot, but the issue comes when I try to use faceting to produce all of the plots at once.
The method I used to add the inset plot is based on this answer: https://stackoverflow.com/a/55635330/11985177
And the method I used to facet the plots across multiple pages in a pdf is based on this answer: https://stackoverflow.com/a/48544261/11985177
require(ggplot2)
require(ggforce)
require(ggpmisc)
#create example dataframe
exampledf<- data.frame("Time"= rep(1:50, 10), "Type"= rep(1:10, each=50), "Var1"= rnorm(1000), "Var2"= rnorm(1000))
graph_inset_facet<- function(df){
mainplot<- ggplot(df,
aes(x=Time, y=value))+
geom_point(aes(y=Var1, color= "Var1"))+
geom_point(aes(y= Var2, color="Var2"))
insetdf<-tibble(x = 0.9, y = 0.9,
plot = list(mainplot +
coord_cartesian(xlim = c(40, 45)) +
labs(x = NULL, y = NULL)))
mainplot +
expand_limits(x = 0, y = 0) +
geom_plot_npc(data = insetdf, aes(npcx = x, npcy = y, label = plot))
#wd is working directory
pdf(file = paste(wd, "facet inset.pdf"))
for(i in 1:2){
print(mainplot+
facet_grid_paginate(df$Type, nrow = 5, ncol = 1, page = i))
}
dev.off()
}
This code does print a pdf with the main plots faceted by "Type", but the inset plots don't show up. I tried running the code with the expand_limits and geom_plot_npc functions inside the print for loop, but the inset graphs still didn't show up.