Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust title position in ggplot2

Tags:

r

ggplot2

Here is the code:

require(ggplot2)
require(grid)
# pdf("a.pdf")
png('a.png')
a <- qplot(date, unemploy, data = economics, geom = "line") + opts(title='A')
b <- qplot(uempmed, unemploy, data = economics) + geom_smooth(se = F) + opts(title='B')
c <- qplot(uempmed, unemploy, data = economics, geom="path") + opts(title='C')
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 2)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
print(a, vp = vplayout(1, 1:2))
print(b, vp = vplayout(2, 1))
print(c, vp = vplayout(2, 2))
dev.off()

And result:

enter image description here

While here is what I would like to have, i.e. to position titles near the top of y-axis:

enter image description here

like image 252
qed Avatar asked Oct 27 '13 18:10

qed


People also ask

How do I change the position of a title in R?

You can adjust the position of the title with the adj argument, that takes values from 0 (left-justified) to 1 (right-justified). Default value is 0.5. However, if you specify the argument adj inside your plotting function all text will be adjusted. If you only want some texts adjusted use it inside the title function.

How do I change the position of a caption in ggplot2?

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.

Which method should be used to change the title of a plot?

Directly by specifying the titles to the plotting function (ex : plot() ). In this case titles are modified during the creation of plot. the title() function can also be used. It adds titles on an existing plot.


1 Answers

What you are looking for is theme(plot.title = element_text(hjust = 0)). For example, using the latest version of ggplot2 and theme instead of opts we have

a <- qplot(date, unemploy, data = economics, geom = "line") + ggtitle("A") +
  theme(plot.title = element_text(hjust = 0))

Alternatively, staying with opts

a <- qplot(date, unemploy, data = economics, geom = "line") + 
  opts(title = "A", plot.title = element_text(hjust = 0))

enter image description here

like image 189
Julius Vainora Avatar answered Sep 28 '22 18:09

Julius Vainora