在振幅为索引、频率为列的速度DataFrame中,找各列最接近6的元素并绘带标记热力图
为热力图每一列标记最接近指定值的元素位置
实现步骤
- 定位每列目标元素:计算每个单元格数值与指定值(6)的绝对差值,找出每列中差值最小的元素,记录其行索引(振幅值)和对应速度值。
- 热力图坐标转换:由于热力图的y轴顺序与DataFrame行顺序相反,需将DataFrame的索引位置转换为热力图的实际坐标。
- 标记目标位置:用黄色线条在热力图上标记出每列的目标元素位置。
完整代码
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 创建示例DataFrame c1 = [6, 3, 2, 3, 8, 2] c2 = [1, 5.2, 2, 7, 3, 4] c3 = [3, 5, 6.1, 3, 4, 5.7] c4 = [5, 8, 1, 6.2, 3, 4] c5 = [1, 2, 5, 5, 6.3, 7] c6 = [1, 3, 5.5, 1, 7, 6.1] df = pd.DataFrame([c1, c2, c3, c4, c5, c6]).T # 设置索引(振幅)和列名(频率) index = pd.Index(['0.1', '0.2', '0.3', '0.4', '0.5', '0.6']) df = df.set_index(index) df.columns = ['1', '2', '3', '4', '5', '6'] # 找出每列最接近6的元素的行索引和对应数值 target_value = 6 closest_indices = df.sub(target_value).abs().idxmin(axis=0) closest_values = [df.loc[idx, col] for col, idx in closest_indices.items()] # 打印验证结果 print("每列最接近6的元素信息:") for col, idx, val in zip(df.columns, closest_indices, closest_values): print(f"频率{col}Hz:振幅{idx}m,速度值{val}") # 绘制热力图 plt.figure(figsize=(8, 6)) ax = sns.heatmap(df, annot=True, cmap='viridis') plt.ylabel('Amplitude [m]') plt.xlabel('Frequency [Hz]') # 转换坐标:适配热力图y轴逆序的特点 y_coords = [len(df)-1 - df.index.get_loc(idx) for idx in closest_indices] x_coords = list(range(len(df.columns))) # 用黄色横向线条标记目标位置 for x, y in zip(x_coords, y_coords): ax.hlines(y + 0.5, x - 0.5, x + 0.5, color='yellow', linewidth=3) plt.show()
代码说明
- 元素定位:
df.sub(target_value).abs().idxmin(axis=0)通过计算绝对差值找到每列最接近目标值的行索引,再通过列表推导式提取对应速度值。 - 坐标适配:热力图y轴从下到上对应DataFrame的最后一行到第一行,因此需要用
len(df)-1 - 索引位置转换坐标。 - 标记样式:使用
ax.hlines绘制横向黄色线条,也可替换为ax.vlines绘制竖线,或用ax.scatter添加标记点。
内容的提问来源于stack exchange,提问作者Marc Schwambach
相关产品推荐
相关产品推荐

