zach
zach

Reputation: 30983

Position ggplot title at the top right of the plot

I am using the excellent theme_minimal() found in ggplot0.9.3 which has a white background. I would like to place the title of my plots in a custom location at the top right corner of the plot. In the following example I know the x and y values, but I am wondering if there is a way to pass xmax and ymax values to ensure text placement in the top-right. Ideally, the text would be right justified.

#example plot
p <- qplot(mpg, wt, data = mtcars, colour = cyl)
p +  annotate("text", x = 30, y = 5, label = "Custom Title")

#what I would like
p + annotate("text", y= ymax, x =xmax_or_RightJustified)

Upvotes: 21

Views: 26773

Answers (2)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

You can do

p + annotate("text",  x=Inf, y = Inf, label = "Some text", vjust=1, hjust=1)

Upvotes: 56

Didzis Elferts
Didzis Elferts

Reputation: 98429

You can use functions max() and min() inside annotate(), and then add hjust=1 to ensure that text is placed inside plot (justified).

p + annotate("text", y= max(mtcars$wt), x =max(mtcars$mpg),label="Custom Title",hjust=1) 

Upvotes: 20

Related Questions