Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align ggplot title with window rather than plot grid?

Tags:

r

ggplot2

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)

enter image description here

like image 794
Andrie Avatar asked Jun 11 '12 06:06

Andrie


People also ask

How do I change the position of Ggtitle?

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.

Does par work with ggplot?

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.

How do I left align a caption in R?

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.


1 Answers

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.

enter image description here

like image 199
kohske Avatar answered Oct 09 '22 04:10

kohske