如何在 ggplot2中移动或定位图例

我正在尝试创建一个 ggplot2图形,图形下面有一个图例。

Ggplot2在第112页写道: “传说的位置和证明由主题设置 legend.position 控制,值可以是右、左、顶、底、无(没有传说)或数字位置。”。

下面的代码可以工作(因为“ right”是默认值) ,并且它也可以使用“ none”作为图例位置,但是“ left”、“ top”、“ bottom”都会因为“ Error in grid”而失败。图形(“ L _ setviewport”,pvp,TRUE) : 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")

我做错了什么? 重新定位一个传奇必须是难以置信的普遍,所以我认为这是我。

108175 次浏览

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.

You can always place the legend manually - but since the label is still stacked/vertical, it kind of looks ugly. I really hope hadley finds time to fix this :-)

p <- qplot(VarX,VarY, data=myDat, shape=Descrip) +
opts(legend.position=c(.5,0.9),plot.margin = unit(c(6,0,0,0), "lines"))

In newer versions of ggplot2, you can use + theme(legend.position='bottom').

qplot(VarX,VarY, data=myDat, shape=Descrip) +
theme(legend.position='bottom')

enter image description here

See Cookbook for R - Legends for more legends goodness.

In response to a comment, theme_update() doesn't kick in if invoked in the middle of a ggplot (as in + theme_update(), only subsequent times. It also modifies the active theme rather than just the specific plot. So you could do this:

theme_update(legend.position='bottom')
qplot(VarX,VarY, data=myDat, shape=Descrip)

with results as above, with the difference being that subsequent plots will also default to legend on bottom.

As Hadley mentioned, you can move a legend to the bottom with theme(legend.position = "bottom")

Or manually positioned using theme(legend.position = c(.2,.85))

If you want the legend to be horizontal, use theme(legend.position = c(.2,.85), legend.direction = "horizontal")