如何在R语言条形图下方添加与剂量关联的自适应色块图例?
问题
我正在基于某数据集绘制展示突变频率随剂量变化的条形图,希望在该条形图下方添加与每个条形剂量对应的色块式图例,且图例可根据数据集中的样本数量自适应调整。此前找到的类似方案仅支持固定尺寸色块,无法满足需求,特此求助。
当前代码
MF_sample <- read.table(file = "SamplesData.txt", header = TRUE) MF_by_sample<-ggplot(MF_sample, aes(x=sample, y=MFmin, fill=factor(dose))) + geom_col() + scale_fill_manual("Dose (mg/kg-bw/day)", values = c("0" = "#33ffff", "1" = "#00ccff", "2"="#3399ff", "5" = "#000066")) + theme_classic() + theme(text = element_text(size = 11, family="calibri")) + scale_x_discrete (limits=MF_sample$sample) + scale_y_continuous(expand = c(0,1e-9))
数据集
| sample | dose | MFmin | MFmax |
|---|---|---|---|
| Sample1 | 0 | 1.89e-07 | 2.38750e-07 |
| Sample2 | 0 | 2.89e-07 | 2.46467e-07 |
| Sample3 | 1 | 3.89e-07 | 3.04626e-07 |
| Sample4 | 1 | 5.89e-07 | 1.01960e-07 |
| Sample5 | 1 | 7.89e-07 | 1.04370e-07 |
| Sample6 | 2 | 8.89e-07 | 1.98602e-07 |
| Sample7 | 2 | 9.89e-07 | 1.77643e-07 |
| Sample8 | 2 | 1.89e-07 | 1.94386e-07 |
解决方案
可以通过patchwork包将主条形图与一个自适应样本数量的色块图例图垂直拼接,实现需求。具体代码如下:
# 安装并加载所需包 install.packages("patchwork") library(patchwork) library(ggplot2) # 读取数据集 MF_sample <- read.table(file = "SamplesData.txt", header = TRUE) # 绘制主条形图:隐藏x轴标签,留给底部色块图对应 main_plot <- ggplot(MF_sample, aes(x=sample, y=MFmin, fill=factor(dose))) + geom_col() + scale_fill_manual("Dose (mg/kg-bw/day)", values = c("0" = "#33ffff", "1" = "#00ccff", "2"="#3399ff", "5" = "#000066")) + theme_classic() + theme(text = element_text(size = 11, family="calibri"), axis.title.x = element_blank(), axis.text.x = element_blank()) + scale_x_discrete(limits=MF_sample$sample) + scale_y_continuous(expand = c(0,1e-9)) # 绘制底部色块图例图:用tile生成每个样本对应剂量的色块,仅保留核心元素 legend_plot <- ggplot(MF_sample, aes(x=sample, y=1, fill=factor(dose))) + geom_tile(color = "white") + # 白色边框区分色块 scale_fill_manual(values = c("0" = "#33ffff", "1" = "#00ccff", "2"="#3399ff", "5" = "#000066")) + theme_void() + # 移除所有冗余主题元素 theme(legend.position = "none") # 隐藏重复图例 # 拼接两张图,设置高度比例保证色块图不占用过多空间 combined_plot <- main_plot / legend_plot + plot_layout(heights = c(10, 1)) # 输出最终图 print(combined_plot)
方案说明
- 色块图通过
geom_tile生成,完全匹配主图的x轴样本顺序,自动适配样本数量变化 - 主图隐藏x轴标签,让底部色块直接对应每个条形,逻辑更直观
- 复用主图的填充色值,保证颜色一致性
patchwork的布局功能可以灵活调整两张图的高度占比,避免色块图喧宾夺主
内容的提问来源于stack exchange,提问作者DLBScripts
相关产品推荐
相关产品推荐

