[英]Is there a way to change the spacing between legend items in ggplot2?
Is there a way to change the spacing between legend items in ggplot2?有没有办法改变ggplot2中图例项之间的间距? I currently have
我目前有
legend.position ="top"
which automatically produces a horizontal legend.它会自动生成水平图例。 However, the spacing of the items is very close together and I am wondering how to space them farther apart.
但是,项目的间距非常接近,我想知道如何将它们间隔得更远。
ggplot2 v3.0.0
released in July 2018 has working options to modify legend.spacing.x
, legend.spacing.y
and legend.text
. 2018 年 7 月发布的
ggplot2 v3.0.0
具有修改legend.spacing.x
、 legend.spacing.y
和legend.text
工作选项。
Example: Increase horizontal spacing between legend keys示例:增加图例键之间的水平间距
library(ggplot2)
ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) +
geom_bar() +
coord_flip() +
scale_fill_brewer("Cyl", palette = "Dark2") +
theme_minimal(base_size = 14) +
theme(legend.position = 'top',
legend.spacing.x = unit(1.0, 'cm'))
Note: If you only want to expand the spacing to the right of the legend text, use stringr::str_pad()
注意:如果您只想扩大图例文本右侧的间距,请使用
stringr::str_pad()
Example: Move the legend key labels to the bottom and increase vertical spacing示例:将图例键标签移到底部并增加垂直间距
ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) +
geom_bar() +
coord_flip() +
scale_fill_brewer("Cyl", palette = "Dark2") +
theme_minimal(base_size = 14) +
theme(legend.position = 'top',
legend.spacing.x = unit(1.0, 'cm'),
legend.text = element_text(margin = margin(t = 10))) +
guides(fill = guide_legend(title = "Cyl",
label.position = "bottom",
title.position = "left", title.vjust = 1))
Example: for scale_fill_xxx
& guide_colorbar
示例:对于
scale_fill_xxx
和guide_colorbar
ggplot(mtcars, aes(mpg, wt)) +
geom_point(aes(fill = hp), pch = I(21), size = 5)+
scale_fill_viridis_c(guide = FALSE) +
theme_classic(base_size = 14) +
theme(legend.position = 'top',
legend.spacing.x = unit(0.5, 'cm'),
legend.text = element_text(margin = margin(t = 10))) +
guides(fill = guide_colorbar(title = "HP",
label.position = "bottom",
title.position = "left", title.vjust = 1,
# draw border around the legend
frame.colour = "black",
barwidth = 15,
barheight = 1.5))
For vertical legends , setting legend.key.size
only increases the size of the legend keys, not the vertical space between them对于垂直图例,设置
legend.key.size
只会增加图例键的大小,而不是它们之间的垂直空间
ggplot(mtcars) +
aes(x = cyl, fill = factor(cyl)) +
geom_bar() +
scale_fill_brewer("Cyl", palette = "Dark2") +
theme_minimal(base_size = 14) +
theme(legend.key.size = unit(1, "cm"))
In order to increase the distance between legend keys, modification of the legend-draw.r
function is needed.为了增加图例键之间的距离,需要修改
legend-draw.r
函数。 See this issue for more info有关更多信息,请参阅此问题
# function to increase vertical spacing between legend keys
# @clauswilke
draw_key_polygon3 <- function(data, params, size) {
lwd <- min(data$size, min(size) / 4)
grid::rectGrob(
width = grid::unit(0.6, "npc"),
height = grid::unit(0.6, "npc"),
gp = grid::gpar(
col = data$colour,
fill = alpha(data$fill, data$alpha),
lty = data$linetype,
lwd = lwd * .pt,
linejoin = "mitre"
))
}
### this step is not needed anymore per tjebo's comment below
### see also: https://ggplot2.tidyverse.org/reference/draw_key.html
# register new key drawing function,
# the effect is global & persistent throughout the R session
# GeomBar$draw_key = draw_key_polygon3
ggplot(mtcars) +
aes(x = cyl, fill = factor(cyl)) +
geom_bar(key_glyph = "polygon3") +
scale_fill_brewer("Cyl", palette = "Dark2") +
theme_minimal(base_size = 14) +
theme(legend.key = element_rect(color = NA, fill = NA),
legend.key.size = unit(1.5, "cm")) +
theme(legend.title.align = 0.5)
I think the best option is to use guide_legend
within guides
:我认为最好的选择是在
guides
使用guide_legend
:
p + guides(fill=guide_legend(
keywidth=0.1,
keyheight=0.1,
default.unit="inch")
)
Note the use of default.unit
, no need to load grid
package.注意使用
default.unit
,不需要加载grid
包。
A simple fix that I use to add space in horizontal legends, simply add spaces in the labels (see extract below):我用来在水平图例中添加空格的简单修复,只需在标签中添加空格(请参阅下面的摘录):
scale_fill_manual(values=c("red","blue","white"),
labels=c("Label of category 1 ",
"Label of category 2 ",
"Label of category 3"))
Now that opts
is deprecated in ggplot2
package, function theme
should be used instead:现在
ggplot2
包中不推荐使用opts
,应改用函数theme
:
library(grid) # for unit()
... + theme(legend.key.height=unit(3,"line"))
... + theme(legend.key.width=unit(3,"line"))
To add spacing between entries in a legend, adjust the margins of the theme element legend.text
.要在图例中的条目之间添加间距,请调整主题元素
legend.text
的边距。
To add 30pt of space to the right of each legend label (may be useful for a horizontal legend):在每个图例标签的右侧添加 30pt 的空间(可能对水平图例有用):
p + theme(legend.text = element_text(
margin = margin(r = 30, unit = "pt")))
To add 30pt of space to the left of each legend label (may be useful for a vertical legend):要在每个图例标签的左侧添加 30pt 的空间(可能对垂直图例有用):
p + theme(legend.text = element_text(
margin = margin(l = 30, unit = "pt")))
for a ggplot2
object p
.对于
ggplot2
对象p
。 The keywords are legend.text
and margin
.关键字是
legend.text
和margin
。
[Note about edit: When this answer was first posted, there was a bug. [关于编辑的注意事项:当这个答案第一次发布时,有一个错误。 The bug has now been fixed]
该错误现已修复]
Looks like the best approach (in 2018) is to use legend.key.size
under the theme
object.看起来最好的方法(2018 年)是在
theme
对象下使用legend.key.size
。 (eg, see here ). (例如,见这里)。
#Set-up:
library(ggplot2)
library(gridExtra)
gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
geom_point()
This is real easy if you are using theme_bw()
:如果您使用
theme_bw()
这真的很容易:
gpbw <- gp + theme_bw()
#Change spacing size:
g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1bw,g2bw,g3bw,nrow=3)
However, this doesn't work quite so well otherwise (eg, if you need the grey background on your legend symbol):但是,否则这不会很好地工作(例如,如果您需要图例符号上的灰色背景):
g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
g3 <- gp + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1,g2,g3,nrow=3)
#Notice that the legend symbol squares get bigger (that's what legend.key.size does).
#Let's [indirectly] "control" that, too:
gp2 <- g3
g4 <- gp2 + theme(legend.key = element_rect(size = 1))
g5 <- gp2 + theme(legend.key = element_rect(size = 3))
g6 <- gp2 + theme(legend.key = element_rect(size = 10))
grid.arrange(g4,g5,g6,nrow=3) #see picture below, left
Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).请注意,白色方块开始阻塞图例标题(如果我们不断增加值,最终会阻塞图形本身)。
#This shows you why:
gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))
I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!我还没有找到解决上述问题的解决方法......如果您有任何想法,请在评论中告诉我,我会相应地更新!
$layers
...$layers
重新$layers
...From Koshke's work on ggplot2 and his blog ( Koshke's blog )来自 Koshke 在 ggplot2 上的工作和他的博客( Koshke 的博客)
... + theme(legend.key.height=unit(3,"line")) # Change 3 to X
... + theme(legend.key.width=unit(3,"line")) # Change 3 to X
Type theme_get()
in the console to see other editable legend attributes.在控制台中键入
theme_get()
以查看其他可编辑的图例属性。
Use any of these使用这些中的任何一个
legend.spacing = unit(1,"cm")
legend.spacing.x = unit(1,"cm")
legend.spacing.y = unit(1,"cm")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.