1

I'm trying two combine to plots created with ggplot2 that have the same x axis into one figure. I basically followed the instructions found here: https://gist.github.com/tomhopper/faa24797bb44addeba79.

I modified the code to be as follows:

library(ggplot2)
library(grid)
library(dplyr)
library(lubridate)

df <- data.frame(DateTime = ymd("2010-07-01") + c(0:8760) * hours(2), series1 = rnorm(8761), series2 = rnorm(8761, 100))
df_1<- df %>% select(DateTime, series1) %>% na.omit()
df_2 <- df %>% select(DateTime, series2) %>% na.omit()


plot1 <- ggplot(df_1) +
    geom_point(aes(x = DateTime, y = series1), size = 0.5, alpha = 0.75) +
    labs(x="", y="Red dots / m") +
    theme(axis.title.x = element_blank(), axis.text.x=element_blank())

plot2 <- ggplot(df_2) +
    geom_point(aes(x = DateTime, y = series2), size = 0.5, alpha = 0.75) +
    labs(x="", y="Blue drops / L") +
    theme(axis.title.x = element_blank())

grid.newpage()
grid.draw(rbind(ggplotGrob(plot1), ggplotGrob(plot2), size = "last"))

This gives me the following picture:

the two plots

How can I remove the space between the plots? I tried to change the margins in each separate plot with theme(plot.margin = unit(c(-1,1.2,0,0), "cm")), but this gets lost when combining the plots in grid.draw.

I know that there are similar posts, but I cannot find any solution which works for my case. I would appreciate any hints on this!

wylierose
  • 79
  • 5
  • With this example, you might be better off using facets. If you want to fix the margins, remember to remove the relevant margin of both plots – Richard Telford Feb 07 '20 at 11:54

1 Answers1

2

You can follow the approach from this question to set the bottom margin of plot.margin as negative in the first/upper plot and the top margin of the plot.margin argument as negative in the second/lower plot. It might take some finessing of what negative values to use, but you should be able to find something that works for you!

library(ggplot2)
library(grid)
library(dplyr)
library(lubridate)

df <- data.frame(DateTime = ymd("2010-07-01") + c(0:8760) * hours(2), series1 = rnorm(8761), series2 = rnorm(8761, 100))
df_1<- df %>% select(DateTime, series1) %>% na.omit()
df_2 <- df %>% select(DateTime, series2) %>% na.omit()


plot1 <- ggplot(df_1) +
    geom_point(aes(x = DateTime, y = series1), size = 0.5, alpha = 0.75) +
    labs(x="", y="Red dots / m") +
    theme(axis.title.x = element_blank(), axis.text.x=element_blank(),
          plot.margin=unit(c(0.9,1,-0.175,1), "cm"))

plot2 <- ggplot(df_2) +
    geom_point(aes(x = DateTime, y = series2), size = 0.5, alpha = 0.75) +
    labs(x="", y="Blue drops / L") +
    theme(axis.title.x = element_blank(),
          plot.margin=unit(c(-0.175,1,0.9,1), "cm")
          )

grid.newpage()
grid.draw(rbind(ggplotGrob(plot1), ggplotGrob(plot2), size = "last"))

With the output: enter image description here

krfurlong
  • 867
  • 6
  • 17