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

如何在ggplot中居中图例文本并优化图例颜色与文本间距

解决方案

要实现图例文本居中,并增加颜色块与文本的间距,只需调整theme()中与图例相关的参数,具体修改如下:

关键参数调整

  • 图例文本居中:将legend.text的hjust设置为0.5,同时移除原代码中过大的右侧边距(margin(r = 6.2, unit = "cm")),避免文本偏移。
  • 增加颜色块与文本的间距:通过给legend.text添加左侧边距(margin(l = unit(0.3, "cm"))),或者调整legend.key.width扩大颜色块宽度,两者配合能让间距更合理。
  • 优化图例整体布局:调整legend.spacing.x到合适数值(比如unit(0.5, "cm")),避免图例项之间过于松散。

修改后的完整代码

# 数据
df <- structure(list(zone = c("Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Total", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Total"), 
                     effort = c(3226, 4705, 2443, 131, 276, 10781, 1757, 7293, 1631, 34.4, 442, 11157), 
                     creelyear = c("2013-2014", "2013-2014", "2013-2014", "2013-2014", "2013-2014", "2013-2014", "2022-2023", "2022-2023", "2022-2023", "2022-2023", "2022-2023", "2022-2023")), 
                class = "data.frame", row.names = c(NA, -12L))

# 绘图代码
library(ggplot2)
library(scales) # 用于comma函数

df %>% 
  ggplot(aes(x= zone, y= effort, fill=creelyear)) + 
  geom_bar(position="dodge",  stat="identity", color = "black") + 
  scale_y_continuous(labels = comma, name = "Pressure (h/km)", limits = c(0,12000), expand = c(0, 0)) + 
  scale_fill_manual(name = "", labels = c("2013-2014", "2022-2023"), values = c("#000000","#d11141"))+ 
  scale_x_discrete(limits = c("Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Total")) + 
  xlab("Zone") + 
  theme(
    legend.position = 'top', 
    legend.spacing.x = unit(0.5, 'cm'), # 调整图例项之间的水平间距
    legend.background = element_blank(), 
    legend.box.background = element_rect(colour = "black"), 
    legend.text = element_text(
      hjust = 0.5, # 文本居中
      margin = margin(l = unit(0.3, "cm")) # 增加颜色块与文本的左侧间距
    ),
    legend.key.width = unit(0.8, "cm"), # 可选:扩大颜色块宽度,进一步优化间距
    panel.background = element_rect(fill='transparent'), 
    plot.background = element_rect(fill='transparent', color = "transparent"), 
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(), 
    panel.border = element_rect(colour = "black", fill=NA, size=1)
  )

效果说明

  • 图例文本会相对于颜色块居中显示,不再偏移。
  • 颜色块与文本之间的间距适中,整体布局更协调美观。
  • 图例项之间的间距经过调整,不会过于松散或拥挤。

内容的提问来源于stack exchange,提问作者Ryan Gary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:23:22