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

R ggplot2如何垂直对齐图例框元素 实现标题居上色条横向布局

ggplot2 水平渐变图例标题居顶设置方法

核心调整逻辑

要实现颜色渐变条水平对齐、图例标题显示在渐变条正上方的效果,不需要修改现有基础主题配置,只需要通过guides()函数单独指定颜色映射对应的图例样式即可,涉及3个核心参数:

  • direction = "horizontal":指定颜色渐变条为水平排布
  • title.position = "top":将图例标题放置在渐变条的上方区域
  • title.hjust = 0.5:设置标题水平居中对齐,刚好落在渐变条正上方

如果默认水平色条长度过短,还可以通过barwidth参数手动指定色条宽度,适配图幅尺寸。

修改后完整代码

library(ggplot2)
library(grid)
theme_set(theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.position=c(0,1),
        legend.justification = c(0,1),
        legend.box.margin = margin(5, l = 5, unit = 'mm'),
        legend.box = 'horizontal'
        ))

ggplot(diamonds,aes(x,y,color=z))+
  geom_point()+
  scale_colour_gradient2('Time [min]',
                         low='lightgray',
                         mid='red3',
                         high='red4',
                         midpoint=15) +
  # 新增图例配置块
  guides(
    colour = guide_colorbar(
      direction = "horizontal",
      title.position = "top",
      title.hjust = 0.5,
      barwidth = unit(30, "mm") # 可根据实际图幅调整色条宽度
    )
  )

内容的提问来源于stack exchange,提问作者Brian Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 21:03:40