Closed
Description
In situations when we want to remove margins, we must set both ticks and ticks length to remove the width/heigth of axis in the underlying gtable. As user would expect the empty size when they remove the axis using element_blank()
.
Issue in stackoverflow: https://stackoverflow.com/questions/40407498/how-to-remove-margins-in-ggplot2-chart
Please note the 10th height which is the height of the axis grob.
library(ggplot2)
p1 <- ggplot(mtcars) +
geom_point(aes(mpg, disp)) +
theme(
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
plot.margin = margin()
)
ggplotGrob(p1)$heights
#> [1] 0points
#> [2] 0points
#> [3] 0cm
#> [4] 0cm
#> [5] 0cm
#> [6] 0points
#> [7] 0cm
#> [8] 0cm
#> [9] 1null
#> [10] sum(0.0966514459665145cm, max(0points, -0.0966514459665145cm), 0cm, 0cm)
#> [11] 0cm
#> [12] 0points
#> [13] 0cm
#> [14] 0cm
#> [15] 0points
#> [16] 0points
ggplotGrob(p1 +
theme(axis.ticks.length = unit(0, "mm")))$heights
#> [1] 0points 0points
#> [3] 0cm 0cm
#> [5] 0cm 0points
#> [7] 0cm 0cm
#> [9] 1null sum(0cm, max(0points, 0cm), 0cm, 0cm)
#> [11] 0cm 0points
#> [13] 0cm 0cm
#> [15] 0points 0points
Created on 2024-09-01 with reprex v2.1.0