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

R语言ggplot2绘制热图时设置垂直图例并实现图例标题居中

ggplot2 热图垂直居中图例调整方案

问题根源

切换图例方向时未同步匹配色条尺寸、标题对齐、图例锚点参数,导致色条变形、位置偏移、标题错位。

需要调整的核心参数

  • 将guides()中guide_colourbar()的direction参数修改为"vertical"
  • 交换色条宽高值:垂直图例需要竖长形态,将原横版配置的barwidth = 5, barheight = 1调整为适配竖版的barwidth = 1, barheight = 8(高度值可根据你的绘图尺寸按需微调)
  • 保留title.position = "top"的同时,新增title.hjust = 0.5参数,强制图例标题在色条上方水平居中
  • 在theme()中新增legend.justification = c(0.5, 0.5)配置,将图例整体锚定在垂直居中位置,解决上移问题

修正后可直接运行的代码

# 未加载ggplot2请先运行 install.packages("ggplot2") 后再执行加载
library(ggplot2)

ggplot(heat, aes(Samples, Gene, fill= log(Folded_Change_of_Expression))) +
  geom_tile()+
  theme(axis.text.x = element_text(angle = 90))+ 
  theme(axis.text.y = element_text(size = 12)) +
  coord_fixed(ratio = 4)+
  theme(panel.background = element_blank()) +
  theme(axis.title = element_text(size = 16)) +
  # 固定图例垂直居中
  theme(legend.justification = c(0.5, 0.5)) +
  guides(fill = guide_colourbar(
    barwidth = 1, 
    barheight = 8, 
    title = "log(Folded Change of Expression)",
    title.position = "top",
    title.hjust = 0.5,
    direction = "vertical"
  ))

可选微调项

  • 如果觉得色条长度不符合预期,直接修改barheight数值即可,数值越大色条越长
  • 如果需要调整图例和绘图区的间距,可以在theme()里添加legend.margin = margin(t = 0, b = 0, l = 10, r = 0)按需调整四个方向的边距
  • 如果需要标题放在色条左侧/右侧和色条平行、垂直居中,只需要把title.position改为"left"/"right",同时将title.hjust = 0.5替换为title.vjust = 0.5即可

内容的提问来源于stack exchange,提问作者Mostafa Alaverdi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 20:39:17