如何用ggplot绘制单框架物种丰富度与多样性条形图并添加顶部图例
R语言ggplot绘制物种丰富度条形图解决方案
数据预处理
ggplot要求输入长格式数据,先对你的原始矩阵做格式转换:
# 加载依赖包 library(ggplot2) library(tidyr) # 你的原始数据集 datalw <- as.matrix(data.frame(Bng = c(8, 0.4), Krs= c(3, 0), Bny= c(3, 0), Kmb= c(9.1, 7.40), Sgk= c(3, 0.3), Lwb= c(6.4, 1.0), Lws= c(4.3, 0.7), Krm= c(3, 0.5), Hrt= c(7, 0.5), Gmb= c(6.5, 1.0))) rownames(datalw) <- c("Estimates", "s.e") # 转置为长格式数据框,适配ggplot绘图逻辑 df <- as.data.frame(t(datalw)) df$site <- rownames(df)
单张条形图绘制(图例置于顶部)
实现带误差棒、顶部图例的效果,代码如下:
ggplot(df, aes(x = site, y = Estimates)) + # 绘制丰富度估计值条形 geom_col(aes(fill = "Estimates"), color = "black") + # 绘制标准误误差棒 geom_errorbar(aes(ymin = Estimates - s.e, ymax = Estimates + s.e, color = "Standard Error"), width = 0.2, linewidth = 0.8) + # 自定义坐标轴和图例标签 labs(x = "采样点", y = "物种丰富度估计值", fill = NULL, color = NULL) + # 自定义配色 scale_fill_manual(values = "#1b98e0") + scale_color_manual(values = "#353436") + # 设置图例置于顶部,横向排列 theme( legend.position = "top", legend.box = "horizontal" )
同一框架放置多张图
ggplot场景:使用patchwork包
patchwork是专门用于ggplot多图排版的包,比基础绘图的par参数适配性更强:
# 安装加载包 # install.packages("patchwork") library(patchwork) # 生成第一个图(物种丰富度) p1 <- ggplot(df, aes(x = site, y = Estimates)) + geom_col(aes(fill = "Estimates"), color = "black") + geom_errorbar(aes(ymin = Estimates - s.e, ymax = Estimates + s.e, color = "Standard Error"), width = 0.2, linewidth = 0.8) + labs(x = "采样点", y = "物种丰富度", fill = NULL, color = NULL) + scale_fill_manual(values = "#1b98e0") + scale_color_manual(values = "#353436") + theme(legend.position = "top") # 生成第二个图(示例为模拟的Shannon多样性数据,可替换为你的真实多样性数据) p2 <- ggplot(df, aes(x = site, y = runif(nrow(df), 1, 3))) + geom_col(fill = "#2ecc71", color = "black") + labs(x = "采样点", y = "Shannon多样性指数") + theme(legend.position = "top") # 1行2列横向排列两张图 p1 + p2 # 若需2行1列纵向排列,替换为 p1 / p2
基础绘图场景:使用par(mfrow)参数
你提到的parfrow为拼写误差,正确用法如下:
# 设置1行2列的布局,mar参数调整边距避免内容挤压 par(mfrow = c(1,2), mar = c(4,4,2,1)) # 绘制第一张图 barplot(datalw, col = c("#1b98e0", "#353436"), main = "物种丰富度") legend("top", legend = c("estimates", "s.e"), fill = c("#1b98e0", "#353436"), bty = "n", horiz = TRUE) # 绘制第二张图(示例为缩放后的模拟数据,可替换为你的真实多样性数据) barplot(datalw * 0.8, col = c("#2ecc71", "#f39c12"), main = "Shannon多样性") legend("top", legend = c("estimates", "s.e"), fill = c("#2ecc71", "#f39c12"), bty = "n", horiz = TRUE) # 绘图完成后重置默认布局 par(mfrow = c(1,1))
内容的提问来源于stack exchange,提问作者Sufraha Islamia
相关产品推荐
相关产品推荐

