【问题标题】:Trying to create a Seaborn heatmap from a Pandas Dataframe尝试从 Pandas 数据框创建 Seaborn 热图
【发布时间】:2018-10-05 02:48:32
【问题描述】:

这是第一次尝试。我实际上有一个我在程序中生成的列表的字典,但由于这是我第一次尝试这个,我使用一个虚拟字典只是为了测试。

我正在关注这个: python Making heatmap from DataFrame

但我在以下方面失败了:

Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 20, in <module>
    sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)
  File "C:\Users\Mark\AppData\Roaming\Python\Python36\site-packages\seaborn\matrix.py", line 517, in heatmap
    yticklabels, mask)
  File "C:\Users\Mark\AppData\Roaming\Python\Python36\site-packages\seaborn\matrix.py", line 168, in __init__
    cmap, center, robust)
  File "C:\Users\Mark\AppData\Roaming\Python\Python36\site-packages\seaborn\matrix.py", line 205, in _determine_cmap_params
    calc_data = plot_data.data[~np.isnan(plot_data.data)]
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

我的代码:

import pandas as pd
import seaborn as sns


Index = ['key1', 'key2', 'key3', 'key4', 'key5']
Cols = ['A', 'B', 'C', 'D']

testdict = {
    "key1": [1, 2, 3, 4],
    "key2": [5, 6, 7, 8],
    "key3": [9, 10, 11, 12],
    "key4": [13, 14, 15, 16],
    "key5": [17, 18, 19, 20]
}

df = pd.DataFrame(testdict, index=Index, columns=Cols)
df = df.transpose()

sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)

【问题讨论】:

    标签: pandas python-3.6 heatmap seaborn


    【解决方案1】:

    你需要切换你的列和索引标签

    Cols = ['key1', 'key2', 'key3', 'key4', 'key5']
    Index = ['A', 'B', 'C', 'D']
    

    【讨论】:

    • 请原谅这个愚蠢的问题:您的回答使错误消失了,但没有显示任何内容。该程序简单地以错误代码 0 结束。我如何实际显示绘图?另外,有没有办法将绘图保存到文件中? .png 还是别的什么?谢谢。
    • 如果运行脚本或在 jupyter notebook 中使用“%matplotlib inline”启动单元格,则写入 plt.show()。关于保存 plt.savefig('name.png') 将完成这项工作。如果仍然丢失,请谷歌 matplotlib
    • 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2020-02-17
    • 2016-11-21
    • 2019-11-27
    相关资源
    最近更新 更多