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

如何在空白ggplot2绘图中居中显示图例

如何将ggplot图例居中显示在绘图区域内

你可以通过在theme()中设置legend.position和legend.justification参数来实现图例居中,修改后的完整代码如下:

ggplot() +
  geom_hline(aes(yintercept = 0, linetype = "Line 1"), color = "white", size = 1.25) +
  geom_hline(aes(yintercept = 0, linetype = "Line 2"), color = "white", size = 1.25) +
  scale_linetype_manual(name = "Reference Lines", values = rep("dashed", 2), 
                        guide = guide_legend(override.aes = list(color = c("red", "green")))) +
  theme_void() +
  theme(
    legend.position = c(0.5, 0.5),
    legend.justification = c(0.5, 0.5)
  )

核心参数解释:

  • legend.position = c(0.5, 0.5):使用相对坐标定位,(0,0)对应绘图区左下角,(1,1)对应右上角,(0.5,0.5)正好是中心位置。
  • legend.justification = c(0.5, 0.5):让图例的中心点与legend.position指定的坐标点对齐,确保图例完全居中,不会出现偏移。

如果需要微调图例位置,直接修改这两个参数的数值即可,比如c(0.6, 0.4)会将图例移至右下区域。

内容的提问来源于stack exchange,提问作者David Moore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:54:54