Username
Username

Reputation: 3663

How do I left-align a title with a linebreak?

I'm making a chart in ggplot2, and I want to save space in the chart's libebreaking title by left-aligning it. Problem is, using hjust does not work right.

library(ggplot2)

chart <- ggplot(
  data = cars,
  aes(
    x = speed,
    y = dist
  )
) +
  geom_point() +
  labs(
    title = "Here is a very long title that will need a\nlinebreak here",
    subtitle = "This subtitle will also have\na linebreak"
  ) +
  theme(
    plot.title = element_text(
      hjust = -0.1
    )
  )
chart

ggsave(
  filename = "~/Desktop/myplot.png",
  plot = chart,
  # type = "cairo",
  height = 4,
  width = 6,
  dpi = 150)

This produces a chart... enter image description here

I would like the "Here" and "linebreak" to line up with the y-axis title. Is this possible with ggplot2 alone?

Upvotes: 3

Views: 1498

Answers (1)

Tung
Tung

Reputation: 28331

You can use geom_text together with coord_cartesian(clip = "off") which allows drawing plot element outside of the plot panel

library(ggplot2)

ggplot(
  data = cars,
  aes(x = speed,
      y = dist)) +
  geom_point() +
  labs(subtitle = "This subtitle will also have\na linebreak") +
  geom_text(
    x = 1,
    y = 160,
    inherit.aes = FALSE,
    label = "Here is a very long title that will need a\nlinebreak here",
    check_overlap = TRUE,
    hjust = 0,
    size = 6
  ) +
  coord_cartesian(clip = "off") +
  theme(plot.margin = unit(c(4, 1, 1, 1), "lines"))

Another way is to use ggarrange from the egg package which has the top argument that can be used for the title

chart <- ggplot(
  data = cars,
  aes(
    x = speed,
    y = dist)) +
  geom_point() +
  labs(subtitle = "This subtitle will also have\na linebreak")


library(grid)
# devtools::install_github('baptiste/egg')
library(egg)
#> Loading required package: gridExtra

ggarrange(chart, 
          ncol = 1,
          top = textGrob(
            "Here is a very long title that will need a\nlinebreak here",
            gp = gpar(fontface = 1, fontsize = 14),
            hjust = 0,
            x = 0.01)
          )

Created on 2018-09-18 by the reprex package (v0.2.1.9000)

Upvotes: 2

Related Questions