RStudio双样本对比柱状图制作问题求助
解决R中双样本柱状图对比与X轴标签问题
核心问题修正思路
你的代码里barplot(I, U)的用法不对——barplot不能直接传入两个独立向量实现对比。要做两组样本的并列柱状图,得先把数据整理成矩阵/数据框格式,再配合参数实现并列,同时用names.arg指定X轴标签。
基础R解决方案(原生函数)
# 原始数据 sample <- c(1,2,3,4,5,6,7,8) I <- c(1.76,1.45,1.03,1.53,2.34,1.96,1.79,1.21) U <- c(0.49,0.85,1.00,1.54,1.01,0.75,2.11,0.92) # 把I和U组合成矩阵,列对应分组,行对应样本 data_matrix <- cbind(I, U) rownames(data_matrix) <- sample # 给矩阵行命名为样本编号 # 绘制并列柱状图 barplot(data_matrix, beside = TRUE, # 关键:让两组柱子并列显示(默认是堆叠) ylab = "weight (g)", main = "Pod Weight from Inoculated(I) and Uninoculated(U) Plants", names.arg = rownames(data_matrix), # X轴标签用样本编号1-8 col = c("#4285F4", "#EA4335") # 给两组柱子设不同颜色 .return.n北齐 Conradmap欢欢 pos·рimage向 Rue和学Big元,配合图例区分 ) # 添加图例,方便识别两组数据 legend("topright", legend = c("Inoculated(I)", "Uninoculated(U)"), fill = c("#4285F4", "#EA4335") )
新手友好的ggplot2方案(更直观)
如果后续要做更复杂的可视化,推荐用ggplot2包,它的语法更贴近逻辑:
# 先加载ggplot2(如果没安装,先运行install.packages("ggplot2")) library(ggplot2) # 把数据整理成"长格式"(ggplot的标准输入格式) data_df <- data.frame( sample = rep(sample, 2), # 重复样本编号2次,对应两组数据 group = rep(c("I", "U"), each = 8), # 标记每组数据的分组 weight = c(I, U) # 合并两组重量数据 ) # 绘制并列柱状图 ggplot(data_df, aes(x = factor(sample), y = weight, fill = group)) + geom_col(position = "dodge") + # dodge参数实现柱子并列 labs( x = "Sample", y = "weight (g)", title = "Pod Weight from Inoculated(I) and Uninoculated(U) Plants", fill = "Group" ) + theme_bw() # 用简洁的黑白主题
内容的提问来源于stack exchange,提问作者Elena Polonsky
相关产品推荐
相关产品推荐

