gpt4 book ai didi

Python:matplotlib 和 seaborn 之间共享比例

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:58 24 4
gpt4 key购买 nike

我想创建一个seaborn热图,它也有散点图颜色点。我希望最终结果使用散点图的网格,热图的方 block 在散点上“居中”。

不幸的是,我不知道如何在两层之间共享比例,如下面的示例所示。

我能做什么?

非常感谢您的帮助。

%matplotlib inline
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

npoints = 3
x = np.tile(np.arange(npoints), npoints)
df = pd.DataFrame({'x': np.tile(np.arange(npoints), npoints), 'y': np.repeat(np.arange(npoints), npoints)})

df['z'] = 0
df.loc[df['x'] == df['y'], 'z'] = df.loc[df['x'] == df['y'], 'x']
df['c'] = np.random.choice(np.arange(3) + 1, df.shape[0])
df.loc[df['x'] != df['y'], 'c'] = 0

sns.heatmap(df[['x', 'y', 'z']].set_index(['x', 'y'])['z'].unstack())
plt.gca().set_title('Heatmap only')

df.plot(x='x', y='y', color=df['c'], kind='scatter')
plt.gca().set_title('Scatter points only')

fig, ax = plt.subplots()
sns.heatmap(df[['x', 'y', 'z']].set_index(['x', 'y'])['z'].unstack(), ax=ax)
df.plot(x='x', y='y', ax=ax, color=df['c'], kind='scatter')
ax.set_title('Heatmap and scatter points - scales problem')

enter image description here enter image description here enter image description here

最佳答案

解决方法是将分散数据移动 0.5:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

npoints = 3
x = np.tile(np.arange(npoints), npoints)
df = pd.DataFrame({'x': np.tile(np.arange(npoints), npoints), 'y': np.repeat(np.arange(npoints), npoints)})

df['z'] = 0
df.loc[df['x'] == df['y'], 'z'] = df.loc[df['x'] == df['y'], 'x']
df['c'] = np.random.choice(np.arange(3) + 1, df.shape[0])
df.loc[df['x'] != df['y'], 'c'] = 0

fig, ax = plt.subplots()
qp = sns.heatmap(df[['x', 'y', 'z']].set_index(['x', 'y'])['z'].unstack(), ax=ax)
# df.plot(x='x', y='y', ax=ax, color=df['c'], kind='scatter')
ax.scatter(df['x']+0.5,df['y']+0.5,c=df['c'])

ax.set_title('Heatmap and scatter points - scales problem')

plt.show()

结果:

enter image description here

关于Python:matplotlib 和 seaborn 之间共享比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40424058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com