Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move or position a legend in ggplot2

I'm trying to create a ggplot2 plot with the legend beneath the plot.

The ggplot2 book says on p 112 "The position and justification of legends are controlled by the theme setting legend.position, and the value can be right, left, top, bottom, none (no legend), or a numeric position".

The following code works (since "right" it is the default), and it also works with "none" as the legend position, but "left", "top", "bottom", all fail with "Error in grid.Call.graphics("L_setviewport", pvp, TRUE) : Non-finite location and/or size for viewport"

library(ggplot2) (myDat <- data.frame(cbind(VarX=10:1, VarY=runif(10)),      Descrip=sample(LETTERS[1:3], 10, replace=TRUE))) qplot(VarX,VarY, data=myDat, shape=Descrip) +      opts(legend.position="right") 

What am I doing wrong? Re-positioning a legend must be incredibly common, so I figure it's me.

like image 340
Dan Goldstein Avatar asked Jun 01 '10 23:06

Dan Goldstein


People also ask

How do you move a legend position in R?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I move my legend location?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do you move a legend?

You can move the legend to any position within your chart. To move a chart's legend, simply click on it once to select it. (You will know it is selected when handles appear around the perimeter of the legend.) Then use the mouse to click within the legend and drag the legend to the desired position on the chart.

How do I move legend below chart?

Click the chart, and then click the Chart Design tab. Click Add Chart Element > Legend. To change the position of the legend, choose Right, Top, Left, or Bottom.


1 Answers

In versions > 0.9.3 (when opts was deprecated)

theme(legend.position = "bottom") 

Older version:

Unfortunately it's a bug in ggplot2 which I really really hope to fix this summer.

Update:

The bug involving opts(legend.position = "left") has been fixed using the most current version of ggplot2. In addition, version 0.9.0 saw the introduction of guide_legend and guide_colorbar which allow much finer control over the appearance and positioning of items within the legend itself. For instance, the ability specify the number of rows and columns for the legend items.

like image 186
hadley Avatar answered Sep 22 '22 22:09

hadley