In ggplot2
version 0.9 the behaviour of the alignment of a plot title changed. Whereas in v0.8.9 the alignment was relative to the plot window, in v0.9 the alignment is relative to the plotting grid.
Now, whereas I mostly agree that this is desirable behaviour, I quite often have very long plot titles.
Question: Is there a way of aligning the plot title with the plot window rather than the plot grid?
I'm looking for an solution that does automatic alignment of the plot. In other words, manual alignment using hjust
would not work for me (I run this on hundreds of plots for each project).
Any solution that used grid
directly is also acceptable.
Some sample code and plot: (Notice how the title gets truncated at the right of window).
dat <- data.frame(
text = c(
"It made me feel very positive to brand X",
"It was clear and easy to understand",
"I didn't like it al all"),
value=runif(3)
)
library(ggplot2)
ggplot(dat, aes(text, value)) +
geom_bar(stat="identity") +
coord_flip() +
opts(title="Thinking about the ad that you've just seen, do you agree with the following statements? I agree that...") +
theme_bw(16)
To display the title at the at any other position of the plot use theme() function. Within theme() function use plot. title parameter with element_text() function as value to it. Again within this function pass the value for hjust attribute.
One disadvantage for par() is that it cannot work for ggplot, we can see below that the plot should appear on the upper left of the page, but it just happen as if par() isn't written here.
caption. position of the theme function allows aliging the caption to the panel ( "panel" , default) or the whole plot (“ plot ”). Note that the default for the caption is right alignment, so you can set hjust = 0 to move the caption to the left of the whole plot.
In ggplot2 0.9 you can easily change the layout.
p <- ggplot(dat, aes(text, value)) +
geom_bar(stat="identity") +
coord_flip() +
opts(title="Thinking about the ad that you've just seen,\ndo you agree with the following statements?\nI agree that...") +
theme_bw(16)
gt <- ggplot_gtable(ggplot_build(p))
gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(1, max(gt$layout$r))
grid::grid.draw(gt)
Perhaps, in the future version, ggplot2 will provide consistent interfaces for tweaking the layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With