While reproducing an images using ggplot2, there was an interesting requirement. Add a second title to the figure, set the location to the right (it would be nice to make changes to the color and other features). It looks like this:
Using the annotate
function, this approach is not very convenient due to the limitations of panel
.
After searching, the following provides a way to do this: Add ggplot annotation outside the panel? Or two titles? I wonder if there is now a simpler and more direct way to accomplish this.
library(tidyverse)
ggplot(mtcars, aes(wt, mpg)) +
geom_point()+
ggtitle('left')+
annotate("text", label="right",
x=Inf, y=Inf, vjust=1, hjust=1)
One of the recent additions to ggplot since v3.5.1 is the ability to specify x and y co-ordinates of text annotations in npc co-ordinates (i.e. relative to the panel, where the bottom left corner is at x = 0, y = 0, and the top right is x = 1, y = 1). The way to do this is to wrap the desired x and y co-ordinates in I()
.
This makes it easy to place text at a fixed position outside the plotting panel as long as we turn clipping off:
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
coord_cartesian(clip = "off") +
ggtitle('left') +
annotate("text", label = "right", x = I(1), y = I(1), hjust = 1,
vjust = -1, size = 8) +
theme_gray(20)