样本相关性可视化绘图技术咨询:基于S1、S2样本数据集
可视化样本相关程度的可行实现方案
当然有可行的办法!用常用的数据分析工具就能轻松可视化这两个样本(S1、S2)之间的相关程度,下面我结合你给的样本数据,分别用Python和R来给你演示具体实现步骤。
先整理样本数据
首先把你提供的原始数据整理成结构化的格式,方便后续处理:
| 样本 | tis1 | tis2 | tis3 | tis4 | tis5 | tis6 | tis7 | tis8 | tis9 | tis10 | tis11 | tis12 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| S1 | 0 | 0 | 0 | 12.1 | 29.2 | 1.9 | 0.45 | 0.2 | 17.0 | 0.4 | 0.7 | 0.1 |
| S2 | 1 | 2 | 0.4 | 14.1 | 9.2 | 1.8 | 0.7 | 0.9 | 7.0 | 0.3 | 0.7 | 0.3 |
方法1:使用Python(Seaborn + Matplotlib)
Python的数据分析生态非常适合这类可视化需求,我们可以通过相关热力图直接展示样本间的相关系数,再用指标对比折线图辅助观察趋势。
步骤1:导入库并加载数据
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 用字典构建数据框 sample_data = { 'tis1': [0, 1], 'tis2': [0, 2], 'tis3': [0, 0.4], 'tis4': [12.1, 14.1], 'tis5': [29.2, 9.2], 'tis6': [1.9, 1.8], 'tis7': [0.45, 0.7], 'tis8': [0.2, 0.9], 'tis9': [17.0, 7.0], 'tis10': [0.4, 0.3], 'tis11': [0.7, 0.7], 'tis12': [0.1, 0.3] } df = pd.DataFrame(sample_data, index=['S1', 'S2'])
步骤2:绘制相关热力图
热力图可以直观展示两个样本的皮尔逊相关系数(取值范围-1到1,越接近±1相关性越强):
# 转置数据后计算样本间的相关系数 corr_matrix = df.T.corr() # 绘制热力图 plt.figure(figsize=(6, 4)) sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', vmin=-1, vmax=1) plt.title('S1与S2的相关系数热力图') plt.show()
运行后会生成一个带数值标注的热力图,红色代表正相关,蓝色代表负相关,数值直接显示相关程度。
步骤3:绘制指标对比折线图
通过折线图可以直观对比每个tis指标的数值变化趋势,和相关系数结果互相印证:
plt.figure(figsize=(12, 6)) # 转置数据后绘制折线图 df.T.plot(kind='line', marker='o') plt.title('S1与S2的TIS指标对比') plt.xlabel('TIS指标') plt.ylabel('指标数值') plt.legend(title='样本') plt.grid(True) plt.show()
方法2:使用R语言(ggplot2)
如果你习惯用R,ggplot2可以生成更灵活的可视化图表,同样分为相关热力图和指标对比图两步。
步骤1:准备数据
# 加载需要的库 library(ggplot2) library(reshape2) # 创建长格式数据框 sample_data <- data.frame( Sample = rep(c("S1", "S2"), each = 12), Indicator = rep(paste0("tis", 1:12), 2), Value = c(0, 0, 0, 12.1, 29.2, 1.9, 0.45, 0.2, 17.0, 0.4, 0.7, 0.1, 1, 2, 0.4, 14.1, 9.2, 1.8, 0.7, 0.9, 7.0, 0.3, 0.7, 0.3) ) # 转换为宽格式用于计算相关系数 wide_data <- dcast(sample_data, Sample ~ Indicator, value.var = "Value") rownames(wide_data) <- wide_data$Sample wide_data <- wide_data[, -1]
步骤2:绘制相关热力图
# 计算样本间的相关系数并转换为长格式 corr_matrix <- cor(t(wide_data)) corr_df <- melt(corr_matrix) # 绘制热力图 ggplot(corr_df, aes(x=Var1, y=Var2, fill=value)) + geom_tile() + geom_text(aes(label=round(value, 2)), color="white") + scale_fill_gradient2(low="blue", mid="white", high="red", midpoint=0, limits=c(-1,1)) + labs(title="S1与S2的相关系数热力图", x="样本", y="样本") + theme_minimal()
步骤3:绘制指标对比折线图
ggplot(sample_data, aes(x=Indicator, y=Value, group=Sample, color=Sample)) + geom_line(linewidth=1) + geom_point(size=3) + labs(title="S1与S2的TIS指标对比", x="TIS指标", y="指标数值") + theme(axis.text.x = element_text(angle=45, hjust=1)) + theme_minimal()
内容的提问来源于stack exchange,提问作者jonny jeep
相关产品推荐
相关产品推荐

