问题描述
我想用第二张图表(KDEplot,但在本例中我将使用散点图,因为它显示了相同的问题)覆盖了一个热图.
I want to overlay a heatmap with a second chart (a KDEplot, but for this example I'll use a scatterplot, since it shows the same issue).
Seaborn 热图具有分类轴,因此用数字轴覆盖图表不会正确对齐两个图表.
Seaborn heatmaps have categorical axes, so overlaying a chart with numerical axes doesn't line up the two charts properly.
示例:
df = pd.DataFrame({2:[1,2,3],4:[1,3,5],6:[2,4,6]}, index=[3,6,9])
df
2 4 6
3 1 1 2
6 2 3 4
9 3 5 6
fig, ax1 = plt.subplots(1,1)
sb.heatmap(df, ax=ax1, alpha=0.1)
用散点图覆盖它:
fig, ax1 = plt.subplots(1,1)
sb.heatmap(df, ax=ax1, alpha=0.1)
ax1.scatter(x=5,y=5, s=100)
ax1.set_xlim(0,10)
ax1.set_ylim(0,10)
有没有办法说服热图使用列和索引值作为数值?
Is there a way to convince the heatmap to use the column and index values as numerical values?
推荐答案
您无法说服"heatmap
不生成分类图.最好使用另一个使用数字轴的图像图.例如,使用 pcolormesh
图.假设当然是列和行均匀分布.那么,
You cannot "convince" heatmap
not to produce a categorical plot. Best use another image plot, which uses numerical axes. For example, use a pcolormesh
plot. The assumption is of course that the columns and rows are equally spread. Then,
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({2:[1,2,3],4:[1,3,5],6:[2,4,6]}, index=[3,6,9])
c = np.array(df.columns)
x = np.concatenate((c,[c[-1]+np.diff(c)[-1]]))-np.diff(c)[-1]/2.
r = np.array(df.index)
y = np.concatenate((r,[r[-1]+np.diff(r)[-1]]))-np.diff(r)[-1]/2.
X,Y = np.meshgrid(x,y)
fig, ax = plt.subplots(1,1)
pc = ax.pcolormesh(X,Y,df.values, alpha=0.5, cmap="magma")
fig.colorbar(pc)
ax.scatter(x=5,y=5, s=100)
ax.set_xlim(0,10)
ax.set_ylim(0,10)
plt.show()
产生
这篇关于带有数值轴的Seaborn热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!