Adjusting title and caption to the left side of a whole picture

1,156 views
Skip to first unread message

aleksander.zawalich

unread,
Oct 19, 2016, 12:02:59 PM10/19/16
to ggplot2

I have a question on the plot created with ggplot2 package. Let's say we have such a plot:

df = data.frame(
  numbers = seq(1,5),
  labels = c(
    "Brand",
    "Good Brand",
    "The Best Brand",
    "The Best Brand Today",
    "The Best Brand This Month"
  )
)
df = df[order(-df$numbers),]
plot = ggplot(data = df, aes(x=labels, y=numbers))+
  geom_bar(stat="identity", fill='orange')+
  coord_flip()+
  labs(
    title = "Exemplary title",
    caption = "Exemplary caption 1\nExemplary caption number 2"
  )+
  theme(
    plot.title = element_text(hjust = -0.5),
    plot.caption = element_text(hjust = -0.5),
    panel.spacing = unit(c(0,0,0,20), "cm")
  )
plot

Is there any better way to align title and caption to the left side of a picture (not plot, but picture, so in this case there where "The best brand in the world" starts), than making negative vjust values for title and caption?

It is not really the best solution for two reasons:

  • if caption has \n character, it is formatted very strangely and seems to be dependent on caption length,
  • the title length can change, and therefore the vjust values can change too, so they cannot be constant

Baptiste Auguie

unread,
Nov 3, 2016, 4:18:38 PM11/3/16
to ggplot2
try this, 

gridExtra::grid.arrange(plot + labs(title="", caption=""), top = grid::textGrob("title", hjust=0, x=0, gp=grid::gpar(font=2, fontsize=18)), bottom = grid::textGrob("caption\ncaption", hjust=0, x=0, gp=grid::gpar(font=3)))

HTH

b.

Robin Edwards

unread,
Aug 6, 2018, 8:35:02 PM8/6/18
to ggplot2
Hope no-one minds if I pick up on this old issue.

This is a handy workaround by Baptiste, but I do wonder if ggplot devs might consider incorporating this as a theme option?  My reason for this is that
  1. horizontal bar plots are popular choice when labels are long, and for this very reason the title often ends up starting in the middle of the page (see example below); and
  2. this grid approach breaks the pipe and so seems inconsistent with the Tidyverse philosophy.

data_frame(pangram = c('The quick brown fox jumps over the lazy dog',
                     'How vexingly quick daft zebras jump',
                     'Jackdaws love my big sphinx of quartz'), n = c(80,12,8)) %>%
  ggplot(aes(pangram, n)) + geom_bar(stat='identity') +
  coord_flip() + labs(title = 'Incidence of English pangrams')

Anyway just my view!

Robin
London
Reply all
Reply to author
Forward
0 new messages