You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何缩小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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 17:02:25