[英]ggplot2 increase space between legend keys
如何增加ggplot2
图的图例键之间的空间?
library(ggplot2)
ggplot(aes(mpg, wt, colour = factor(cyl)),
, data = mtcars) +
geom_point() +
theme(legend.direction = "horizontal",
legend.position = "bottom") +
guides(color = guide_legend(nrow=2))
我正在寻找一个ggplot2选项,在上图中的(键4和键6)之间添加一种垂直调整? 我应该创建自定义图例键吗?
PS:我想增加不在标签之间的方框之间的空白区域。
想要的情节是:
注意: 没有问题不与另一个问题重复。 我们希望在这里添加已经在多行中的项之间的垂直间距。 在另一个问题中,我们有1行图例,我们想在项目之间添加空格(水平)。
另一种(可能更简单的)解决方案是在代码的theme
部分使用legend.key
和legend.key.size
:
ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
geom_point() +
guides(color = guide_legend(nrow = 2)) +
theme(legend.direction = 'horizontal',
legend.position = 'bottom',
legend.key = element_rect(size = 5),
legend.key.size = unit(1.5, 'lines'))
这给了:
如果您在操作图例之前调用theme_bw
或theme_classic
,则应设置图例矩形的颜色:
legend.key = element_rect(size = 5, color = 'white') #or: color = NA
这里使用gtable
的解决方案。 基本上我正在提取图例grobs表,并在图例表中添加一行。
library(gtable)
library(grid)
## transform the ggplot to a grobs table
p_table <- ggplot_gtable(ggplot_build(p))
## extract legend
leg <- which(sapply(p_table$grobs, function(x) x$name) == "guide-box")
## this is the tricky part !
## add a row in the second position (pos=2)
p_table$grobs[[leg]]$grobs[[1]] <-
gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]],
unit(0.5, "line"), ## you can increase the height here
pos=2) ## since I have 2 rows , I insert it in the middle
plot(p_table)
PS:我不知道如何再次强制表格到剧情! 也许其他人可以在这里提供帮助(我只是在绘制并丢失对象结构)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.