4

I have a plot with some long labels and a long title. I'm using coord_flip(), so there is a lot of space outside of the plot margins due to the labels. By default the title is constrained to the plot margin.

How can I get the title to extend beyond the plot margin (to the left) so that it can span the entire width? Here is an example:

ggplot(diamonds, aes(x = cut)) + 
  geom_bar() + 
  coord_flip() + 
  scale_x_discrete("Cut", 
                   labels = c("Fair" = "Fair and a very long extra thing",
                              "Good" = "Good  and a very long extra thing",
                              "Very Good" = "VG  and a very long extra thing", 
                              "Premium" = "P and a very long extra thing. A very long label, just because", 
                              "Ideal" = "I and a very long extra thing")) + 
  ggtitle("This is my very long title.  Long long title. Very long.  The Longest. We have the best long titles.")

My plot with long labels/title

joran
  • 169,992
  • 32
  • 429
  • 468
jzadra
  • 4,012
  • 2
  • 26
  • 46
  • Maybe [this](http://stackoverflow.com/q/21878974/324364) or [this](http://stackoverflow.com/q/37174316/324364) would be helpful? – joran Mar 21 '17 at 17:06
  • @joran Thanks, I'm not after wrapping the labels (in my actual plot their isn't any free vertical space). I'm just wanting the title to span the entire width. – jzadra Mar 21 '17 at 17:07
  • 1
    Maybe `theme(plot.title = element_text(hjust = 0.95))` then? – joran Mar 21 '17 at 17:11
  • @joran Jesus. I just spent 30 minutes messing with margins and googling to no avail. Now I feel stupid. Thanks for the help! – jzadra Mar 21 '17 at 17:15
  • Yeah, we've all been there. – joran Mar 21 '17 at 17:16
  • 1
    alternatively, `grid.arrange(ggplot(), top = "Title goes here")` places it across the whole viewport, not just over the panel. – baptiste Mar 21 '17 at 18:30

2 Answers2

6

Maybe try this:

+ theme(plot.title = element_text(hjust = 0.95))

to move the title over.

joran
  • 169,992
  • 32
  • 429
  • 468
  • I'm running into a followup problem. When I have a multiline title, the hjust acts differently on each line. I can't seem to find a different setting for justification versus reference point. (Try putting a \n in the ggtitle and using hjust = -.5) – jzadra Aug 21 '17 at 22:11
2

Adding

+ theme(plot.title.position = "plot")

also does the trick, and allows the plot to span the whole width of the plot, even if it is just a short title. I thought I'd leave this here because it took me a while to remember this solution after trying to search for it for a long time, and finding this page multiple times in the process.

Boden_Units
  • 83
  • 2
  • 7