如何在ggplot2中移动或定位图例 [英] How to move or position a legend in ggplot2

查看:411
本文介绍了如何在ggplot2中移动或定位图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



ggplot2书在第112页上说:图例的位置和理由是受控制的通过主题设置legend.position,值可以是右,左,上,下,无(无图例)或数字位置。



以下代码有效(因为right是默认值),它也适用于none作为图例位置,但left,top ,bottom,都会失败,并显示Grid.Call.graphics中的错误(L_setviewport,pvp,TRUE):视口的非有限位置和/或大小

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

我做错了什么?重新定位图例必须非常普遍,所以我认为它是我的。

解决方案

在版本> 0.9.3( opts 已弃用)

 主题(legend.position =bottom) 






旧版本



不幸的是,它是ggplot2中的一个错误,我真的很希望今年夏天能够修复这个错误。

更新:



涉及 opts(legend.position =left)的错误已经修复最新版本的 ggplot2 。另外,版本0.9.0引入了 guide_legend guide_colorbar ,可以更好地控制外观和定位图例中的项目。例如,该功能可指定图例项目的行数和列数。


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.

解决方案

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.

这篇关于如何在ggplot2中移动或定位图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆