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
相关产品推荐
相关产品推荐

