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?
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())
ggMarginal(p, margins = "y", type = "density", alpha = 0.5)
Created on 2025-01-03 with reprex v2.1.1
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