如何缩小ggplot图例中图形之间的间距?
解决ggplot图例圆形贴合的问题
你之前的guide_legend代码未生效,是因为没有将它绑定到对应的填充图例设置中。要缩小图例里圆形的间距,让它们几乎贴合,需要将guide_legend参数正确关联到scale_fill_manual或者通过guides()函数指定,同时配合主题参数调整间距。
修改后的完整代码(两种方式任选其一)
方式1:在scale_fill_manual中直接配置图例
library(ggplot2) pd = ggplot(iris, aes(Sepal.Length, Sepal.Width)) scale_pd = pd + geom_point(aes(fill = Species), pch = 21, alpha = 0.6, size = 4) + labs(title="Iris dispersion", subtitle="Sepal length x Sepal Width per species", caption="", x="Sepal Width (cm)", y = "Sepal length (cm)") + theme_classic() + scale_fill_manual( name="Specie", labels=c("Setosa","Versicolor","Virginica"), values=c("#023047","#ffb703","#ef476f"), guide = guide_legend( keyheight = unit(0.2, "cm"), # 缩小单个图例键的高度 keywidth = unit(0.2, "cm"), # 缩小单个图例键的宽度 legend.spacing.y = unit(0, "cm") # 移除图例项之间的垂直间距 ) ) + theme( legend.spacing.y = unit(0, "cm"), legend.margin = margin(t=0, r=0, b=0, l=0, unit="cm") # 移除图例外边距 ) print(scale_pd)
方式2:用guides()单独设置填充图例
library(ggplot2) pd = ggplot(iris, aes(Sepal.Length, Sepal.Width)) scale_pd = pd + geom_point(aes(fill = Species), pch = 21, alpha = 0.6, size = 4) + labs(title="Iris dispersion", subtitle="Sepal length x Sepal Width per species", caption="", x="Sepal Width (cm)", y = "Sepal length (cm)") + theme_classic() + scale_fill_manual( name="Specie", labels=c("Setosa","Versicolor","Virginica"), values=c("#023047","#ffb703","#ef476f") ) + guides( fill = guide_legend( keyheight = unit(0.2, "cm"), keywidth = unit(0.2, "cm"), legend.spacing.y = unit(0, "cm") ) ) + theme( legend.spacing.y = unit(0, "cm"), legend.margin = margin(t=0, r=0, b=0, l=0, unit="cm") ) print(scale_pd)
关键参数说明
keyheight/keywidth:控制每个图例中圆形的尺寸,缩小数值能让图形更紧凑legend.spacing.y:设置不同物种图例项之间的垂直间距,设为unit(0, "cm")可以让圆形几乎贴合legend.margin:移除图例的外边距,避免多余空白影响紧凑效果
内容的提问来源于stack exchange,提问作者Matheus Pacheco
相关产品推荐
相关产品推荐

