使用 matplotlib 3.7.1 创建seaborn 热图不起作用(它曾经在 matplotlib v3.3.3 中工作)

问题描述 投票:0回答:1

我使用 seaborn 创建热图有一段时间了,但最近我更新到了新版本的 matplotlib,热图似乎没有像以前那样显示。我对两者使用相同的数据集和脚本,结果却截然不同。

在这两种情况下,我都在 conda 环境中使用 matplotlib 和 seaborn。 代码:

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

dir_df = 'dfUnloop.csv'
df = pd.read_csv(str(dir_df))
print(df.sample(10))
df = df.drop(['taken'], axis=1)
print(df.sample(10))
df.astype('float16').dtypes

val = 'th_i2e[ch1-tiss]'
heatmap = pd.pivot_table(df, values= val, columns = 'theta', index='z_plane', aggfunc=np.max)
heatmap.astype('float16').dtypes
print(heatmap.sample(10))

fig, ax = plt.subplots(figsize=(16, 10))
b = sns.heatmap(heatmap, cmap='turbo', ax=ax)#, vmin = vmin, vmax = vmax)#, xticklabels=20, yticklabels=550)
x_pos = ax.get_xticks()
x_pos_new = np.linspace(x_pos[0], x_pos[-1], 19)
x_lab_new = np.arange(-180,200,20)
ax.set_xticks(x_pos_new) 

y_pos = ax.get_yticks()
y_pos_new = np.linspace(y_pos[0], y_pos[-1], 11)
ax.set_yticks(y_pos_new) 

plt.show()

工作版本: matplotlib 3.3.3 / seaborn 0.11.0 / python 3.6 working

无效版本: matplotlib 3.7.1 / seaborn 0.12.2 / python 3.9 not working

可以从以下位置下载 csv 文件:https://drive.google.com/file/d/1ko8yLDvsYdvQGRHGlFeD3NBJ5IpZXTp-/view?usp=sharing

我发现一些旧帖子建议一些设置热图 y 和 x 限制的解决方案,但它们似乎都不适合我。 非常感谢所有建议。

python matplotlib seaborn heatmap
1个回答
0
投票
  • seaborn
    matplotlib
    的高级 API,它在底层实现了很多自动化操作。
  • sns.heatmap
    使用
    matplotlib.axes.Axes.pcolormesh
    ,并自动添加颜色条,并设置 x 和 y 刻度标签以匹配 DataFrame 索引和 DataFrame 列。
    • 直接使用
      pcolormesh
      ,会产生这样的 plot
    • v0.12
      似乎改变了
      sns.heatmap
      的功能。
  • 要生成原始图,请使用
    matplotlib.axes.Axes.pcolor
  • 已在
    python 3.11.4
    pandas 2.0.3
    matplotlib 3.7.1
    seaborn 0.12.2
  • 进行测试
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# read the file
df = pd.read_csv('d:/data/dfUnloop.csv', usecols=[2, 3, 5])

# pivot and aggregate
dfp = df.pivot_table(values='th_i2e[ch1-tiss]', columns='theta', index='z_plane', aggfunc=np.max)

# create the plot
fig, ax = plt.subplots(figsize=(16, 10))
c = ax.pcolor(dfp, cmap='jet', alpha=0.8)

# add the colorbar
fig.colorbar(c, ax=ax)

# set the xtick labels
ax.set_xticks(ticks=ax.get_xticks(), labels=np.linspace(dfp.columns.min(), dfp.columns.max(), 8).round(3))

# set the ytick labels
ax.set_yticks(ticks=ax.get_yticks(), labels=np.linspace(dfp.index.min(), dfp.index.max(), 8).round(3))

# reverse the yaxis to emulate seaborn
ax.invert_yaxis()

© www.soinside.com 2019 - 2024. All rights reserved.