In R I want to make a function which takes an ggplot object and some text and returns and ggplot object by adds text just below the legend (in the right side of the plot, while keeping legend on the right side).
myplot = ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
geom_line()
I want to add text "mean of Sepal.Width = 3.05" (and a box around it) just after the legend. I looked at related questions but they change the position of legend to bottom and do not work as a function rather prints the plot.
A couple of possibilities.
The first uses
annotate()
, and involves positioning the text by trial and error. The x position is adjusted usinghjust
, the y position is selected to be a little below the legend. Note: no border around the text.The second assumes a border is required. The combined text and box is constructed using
grid
. Then the grob is positioned usingannotation_custom()
.ymin
andymax
are set to be a little below the legend.xmin
andxmax
are set by trial and error to get the text and the legend to align.Both methods involve plotting outside the plot panel, so clipping to the plot panel needs to be turned off. But if the text size or length changes, the position of the label needs to be adjusted.
The third method is reasonably robust to changes to text length and size. Similar to method 2, the combined text and box grob is constructed using
grid
. Then, usinggtable
functions, the grob is attached to the legend (to the middle column of the legend).Another easy possibility is to use a caption:
It's not really right below the legend, though: