Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

grob

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

like image 769
tassones Avatar asked May 25 '26 16:05

tassones


1 Answers

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

like image 184
M-- Avatar answered May 27 '26 06:05

M--