Skip to content

element_text() ignores left and right margins for some plot elements #5533

@ccsarapas

Description

@ccsarapas

Left and right margins get ignored for some elements (including plot titles and captions), but work fine for other elements (such as strip and axis labels.

Given this plot:

library(ggplot2)

p <- ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  facet_wrap(vars(cyl)) +
  labs(
    title = "City vs. Highway Mileage by Cylinders", 
    caption = "Values are in MPG."
  ) +
  theme(
    plot.background = element_rect(color = "black", linewidth = 1),
    axis.title.y = element_text(angle = 0, vjust = 0.5),
    strip.text = element_text(hjust = 0)
  )

p

You can change the top and bottom margins for the title and caption, but the left and right margins don't budge:

p + 
  theme(
    plot.title = element_text(margin = margin(20, 20, 20, 20)),
    plot.caption = element_text(margin = margin(20, 20, 20, 20))
  )

But all 4 margins seem to work for axis titles and strip labels:

p +
  theme(
    strip.text = element_text(margin = margin(20, 20, 20, 20)),
    axis.title.y = element_text(margin = margin(20, 20, 20, 20))
  )

Created on 2023-11-22 with reprex v2.0.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions