I have a plot that has data that runs into the area I'd like to use for a legend. Is there a way to have the plot automatically put in something like a header space above the highest data points to fit the legend into?
I can get it to work if I manually enter the ylim()
arguments to expand the size and then give the exact coordinates of where I want the legend located, but I'd prefer to have a more flexible means of doing this as it's a front end for a data base query and the data levels could have very different levels.
You have to add the size of the legend box to the ylim range
Edit 2017:
use ggplot and theme(legend.position = ""):
Original answer 2012: Put the legend on the bottom:
?legend
will tell you:Arguments
x
,y
the
x
andy
co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted byxy.coords
: See ‘Details’.Details:
Arguments
x
,y
, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing andy
is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.The coordinates can be specified in any way which is accepted by
xy.coords
. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).The location may also be specified by setting
x
to a single keyword from the listbottomright
,bottom
,bottomleft
,left
,topleft
,top
,topright
,right
andcenter
. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.Building on @P-Lapointe solution, but making it extremely easy, you could use the maximum values from your data using
max()
and then you re-use those maximum values to set thelegend
xy coordinates. To make sure you don't get beyond the borders, you set upylim
slightly over the maximum values.