rggplot2grob

Reduce white space between title and plot when adding marginal plot to ggplot2


When I add the density distribution to the y-axis margin of a ggplot2 scatterplot, a white space appears between the main plot and the title. How can I prevent this extra white space from being added?

Normal title spacing on scatterplot

library(tidyverse)
library(ggExtra)

(p <- diamonds %>% 
  ggplot(aes(x = carat, y = price)) +
  geom_point() +
  scale_y_log10() +
  annotation_logticks(sides = 'lr') +
  labs(title = 'Diamond Price by Carat') +
  theme_bw())

Adds white space between title and plot

ggMarginal(p, margins = "y", type = "density", alpha = 0.5)

Created on 2025-01-03 with reprex v2.1.1


Solution

  • This is a bit of a hack, but we can change the "height" after creating the object:

    library(tidyverse)
    library(ggExtra)
    
    p <- diamonds %>% 
        ggplot(aes(x = carat, y = price)) +
        geom_point() +
        scale_y_log10() +
        annotation_logticks(sides = 'lr') +
        labs(title = 'Diamond Price by Carat') +
        theme_bw()
    
    g <- ggMarginal(p, margins = "y", type = "density", alpha = 0.5)
    g$heights[2] <- unit(-1, "lines")
    g