如何增加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))
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个ggplot2选项,在上图中的(键4和键6)之间添加一种垂直调整?我应该创建自定义图例键吗?
PS:我想增加不在标签之间的方框之间的空白区域.
想要的情节是:
注意:没有问题不与另一个问题重复.我们希望在这里添加已经在多行中的项之间的垂直间距.在另一个问题中,我们有1行图例,我们想在项目之间添加空格(水平).
Jaa*_*aap 54
另一种(也可能更简单)的解决方案是在代码的一部分中使用legend.key
和:legend.key.size
theme
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'))
Run Code Online (Sandbox Code Playgroud)
这给了:
如果您正在呼叫theme_bw
或theme_classic
在操作图例之前,您应该设置图例矩形的颜色:
legend.key = element_rect(size = 5, color = 'white') #or: color = NA
Run Code Online (Sandbox Code Playgroud)
这里有一个解决方案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)
Run Code Online (Sandbox Code Playgroud)
PS:我不知道如何再次强制表格到剧情!也许其他人可以在这里提供帮助(我只是在绘制并丢失对象结构)