rggplot2cowplot

Is there a way in R using cowplot to align an empty plot created with ggdraw with plots created with ggplot2?


I am running through a large dataset and creating a standard set of plots for a large number of species in that dataset. The premise is quite simple. For some species there will be data to create all the plots.

#produce some data
samples <- data.frame(
  GROUP = c("dog","dog","dog","cat","cat","cat"),
  VAR1 = c(1,3,5,1,3,5),
  VAR2   = c(2,4,6,2,4,6),
  VAR3   = c(2,4,6,NA,NA,NA),
  VAR4   = c(1,2,3,1,2,3),
  VAR5 = c(3,2,1,NA,NA,NA)
)

library(ggplot2)
library(cowplot)

#create 3 plots for a species that has data and join the plots with cowplot
plot1.1<-ggplot(samples[samples$GROUP=="dog",],aes(x=VAR1,y=VAR2))+
  geom_point()+
  theme_bw()

plot2.1<-ggplot(samples[samples$GROUP=="dog",],aes(x=VAR3,y=VAR5))+
  geom_point()+
  theme_bw()

plot3.1<-ggplot(samples[samples$GROUP=="dog",],aes(x=VAR4,y=VAR3))+
  geom_point()+
  theme_bw()

group.plot.1<-(plot1.1 + plot2.1 + plot3.1)
group.plot.1

plots for complete data

But for others there will be no data to support some of the plots so an empty plot is returned. This still looks good and everything lines up fine.

plot1.2<-ggplot(samples[samples$GROUP=="cat",],aes(x=VAR1,y=VAR2))+
  geom_point()+
  theme_bw()

plot2.2<-ggplot(samples[samples$GROUP=="cat",],aes(x=VAR3,y=VAR5))+
  geom_point()+
  theme_bw()

plot3.2<-ggplot(samples[samples$GROUP=="cat",],aes(x=VAR4,y=VAR1))+
  geom_point()+
  theme_bw()

group.plot.2<-(plot1.2 + plot2.2 + plot3.2)
group.plot.2

plots for missing data

For the plots with no data I would like to add a 'No Data' label. I do that using ggdraw but when I group the plots the empty plot with the label no longer lines up with the other plots.

#adding 'No Data' label to empty plot
plot2.2b <- ggdraw(plot2.2)+
  draw_label("No Data", color = "#C0A0A0", size = 10)

group.plot.2b<-(plot1.2 + plot2.2b + plot3.2)
group.plot.2b

plots for missing data with label

How do I get the empty plot to line up with the others again? It feels like there should be an easy solution for this or a better way of adding the label but I have had no success with other approaches. Thanks for your help.


Solution

  • Do you need to create the empty plot with ggdraw()? You can create the same empty plot with {ggplot}, and it will work with {cowplot} as expected:

    plot2.2 <- ggplot(samples[samples$GROUP=="cat",],aes(x=VAR3,y=VAR5))+
      annotate(geom = "text", label = "No data", x = 1, y = 1,
               color = "#C0A0A0", size = 5) +
      theme_bw() +
      theme(axis.text = element_blank(),
            panel.grid = element_blank())