一幅图中两个图例之间的距离较小(例如颜色和尺寸比例) [英] Smaller gap between two legends in one plot (e.g. color and size scale)
问题描述
如何缩小一个绘图中两个参考线之间的距离.在下面的示例中,这两个指南来自颜色和尺寸比例,我想更改两者之间的距离,以使标题尺寸"恰好位于图例点的下方1.在这个例子中是有意义的,但是在我的实际应用中却可以.
how do I reduce the gap between two guides in one plot. In the example below, the two guides are from a color and size scale and I want to change the gap between the two so that the title 'size' is right below the legend-point for 1. Design-wise, it might not make sense in this example but in my actual application it does.
df=data.frame(x=rnorm(100),y=rnorm(100),color=factor(rbinom(100,1,0.5)),size=runif(100))
ggplot(df,aes(x=x,y=y,color=color,size=size)) + geom_point()
这是情节.我想使由绿线和箭头突出显示的间隙更小.
Here is the plot. I would like to make the gap highlighted by the green line and the arrow smaller.
推荐答案
我试图自定义legend
或guide
参数,但找不到解决方案.我希望使用ggplot2设置提供解决方案.
I tried to play to customize legend
or guide
parameters but I can't find a solution. I hope give a solution using ggplot2 settings.
这里有2个基于gtable
和grid
软件包的解决方案.
Here 2 solutions based on the gtable
and grid
packages.
对于gtable
解决方案,代码是从问题.
for the gtable
solution, the code is inspired from this question.
library(gtable)
# Data transformation
data <- ggplot_build(p)
gtable <- ggplot_gtable(data)
# Determining index of legends table
lbox <- which(sapply(gtable$grobs, paste) == "gtable[guide-box]")
# changing the space between the 2 legends: here -0.5 lines
guide <- gtable$grobs[[lbox]]
gtable$grobs[[lbox]]$heights <- unit.c(guide$heights[1:2],
unit(-.5,'lines'), ## you can the GAP here
guide$heights[4:5])
# Plotting
grid.draw(gtable)
类似于使用grid
包(我们在图例的视口中重新绘制)
Similar using the grid
package ( we redraw in the viewport of the legend)
pp <- grid.get('guide',grep=T)
depth <- downViewport(pp$wrapvp$name)
guide <- grid.get('guide',grep=T)
grid.rect(gp=gpar(fill='white'))
guide$heights <- unit.c(guide$heights[1:2],unit(-0.2,'lines'),guide$heights[4],unit(0.1,'lines'))
grid.draw(guide)
upViewport(depth)
这篇关于一幅图中两个图例之间的距离较小(例如颜色和尺寸比例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!