如何用含(x,y,z)的Pandas DataFrame生成热力图?
用Seaborn和Plotly生成热力图的方案
Seaborn 实现方式
Seaborn的heatmap需要宽格式数据(行/列对应两个分类变量,单元格存储热力值),所以得先把你的长格式DataFrame转成宽格式,用pandas.pivot就能快速搞定:
步骤1:重组数据
假设你的DataFrame名为df,执行以下代码完成格式转换:
# 透视转换:行对应Distance,列对应Dose,单元格值为Passrate heatmap_data = df.pivot(index='Distance', columns='Dose', values='Passrate')
如果存在重复的(Dose, Distance)组合,用pivot_table指定聚合方式(比如取均值)处理:
heatmap_data = df.pivot_table(index='Distance', columns='Dose', values='Passrate', aggfunc='mean')
步骤2:绘制热力图
直接调用sns.heatmap即可生成:
import seaborn as sns import matplotlib.pyplot as plt sns.heatmap(heatmap_data, annot=True, cmap='viridis') plt.xlabel('Dose') plt.ylabel('Distance') plt.title('Passrate Heatmap') plt.show()
Plotly 实现方式
Plotly提供了更灵活的选项,无需重组数据就能直接生成热力图,完全匹配你想要的简便调用逻辑:
方式1:Plotly Express(推荐,零数据重组)
px.density_heatmap可以直接接收长格式DataFrame,指定x、y、z参数即可:
import plotly.express as px fig = px.density_heatmap(df, x='Dose', y='Distance', z='Passrate', color_continuous_scale='viridis', labels={'Passrate': '通过率'}) fig.update_layout(title='Passrate Heatmap', xaxis_title='Dose', yaxis_title='Distance') fig.show()
如果需要更精细的视觉控制(比如自定义色阶、添加单元格注释),可以用px.imshow,但需要先转成宽格式:
heatmap_data = df.pivot(index='Distance', columns='Dose', values='Passrate') fig = px.imshow(heatmap_data, x=heatmap_data.columns, y=heatmap_data.index, color_continuous_scale='viridis', labels={'x':'Dose', 'y':'Distance', 'color':'Passrate'}) fig.update_layout(title='Passrate Heatmap') fig.show()
方式2:Plotly Graph Objects(底层控制)
如果需要高度自定义图表细节,用go.Heatmap,同样需要先转成宽格式:
import plotly.graph_objects as go heatmap_data = df.pivot(index='Distance', columns='Dose', values='Passrate') fig = go.Figure(data=go.Heatmap( z=heatmap_data.values, x=heatmap_data.columns, y=heatmap_data.index, colorscale='viridis', text=heatmap_data.values, texttemplate="%{text}", textfont={"size":10})) fig.update_layout(title='Passrate Heatmap', xaxis_title='Dose', yaxis_title='Distance') fig.show()
内容的提问来源于stack exchange,提问作者Gavin Kirby
相关产品推荐
相关产品推荐

