python - 使用 Pandas 数据框中的值注释热图

标签 python text matplotlib pandas heatmap

我想用从数据帧传递到下面函数的值来注释热图。我查看了 matplotlib.text 但无法在我的热图中以所需的方式从我的数据框中获取值。我在下面粘贴了用于生成热图的函数,然后是我的数据框和热图调用的输出。我想在热图中每个单元格的中心绘制数据框中的每个值。

生成热图的函数:

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

def heatmap_binary(df,
            edgecolors='w',
            #cmap=mpl.cm.RdYlGn,
            log=False):    
    width = len(df.columns)/7*10
    height = len(df.index)/7*10

    fig, ax = plt.subplots(figsize=(20,10))#(figsize=(width,height))

    cmap, norm = mcolors.from_levels_and_colors([0, 0.05, 1],['Teal', 'MidnightBlue'] ) # ['MidnightBlue', Teal]['Darkgreen', 'Darkred']

    heatmap = ax.pcolor(df ,
                        edgecolors=edgecolors,  # put white lines between squares in heatmap
                        cmap=cmap,
                        norm=norm)


    ax.autoscale(tight=True)  # get rid of whitespace in margins of heatmap
    ax.set_aspect('equal')  # ensure heatmap cells are square
    ax.xaxis.set_ticks_position('top')  # put column labels at the top
    ax.tick_params(bottom='off', top='off', left='off', right='off')  # turn off ticks

    plt.yticks(np.arange(len(df.index)) + 0.5, df.index, size=20)
    plt.xticks(np.arange(len(df.columns)) + 0.5, df.columns, rotation=90, size= 15)

    # ugliness from http://matplotlib.org/users/tight_layout_guide.html
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", "3%", pad="1%")
    plt.colorbar(heatmap, cax=cax)


plt.show()

这是我的数据框的一个例子:

dataframe :

             0-5 km / h  5-40 km / h  40-80 km / h  80-120 km / h  \
NORDIC         0.113955     0.191888      0.017485      -0.277528   
MIDDLE  EU     0.117903     0.197084     -0.001447      -0.332677   
KOREA          0.314008     0.236503     -0.067174      -0.396518   
CHINA          0.314008     0.236503     -0.067174      -0.396518   

             120-160 km / h  160-190 km / h  190 km / h  
NORDIC            -0.054365        0.006107    0.002458  
MIDDLE  EU         0.002441        0.012097    0.004599  
KOREA             -0.087191        0.000331    0.000040  
CHINA             -0.087191        0.000331    0.000040  

生成热图:

heatmap_binary(dataframe)

enter image description here

有什么想法吗?


更新以澄清我的问题

我尝试了问题中提出的解决方案,结果是我正在寻找的: how to annotate heatmap with text in matplotlib? 但是,我在使用 matplotlib.text 函数定位热图中的值时仍然遇到问题: 这是我尝试此解决方案的鳕鱼:

import matplotlib.pyplot as plt
import numpy as np


data = dataframe.values
heatmap_binary(dataframe)

for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        plt.text(data[y,x] +0.05 , data[y,x] + 0.05, '%.4f' % data[y, x], #data[y,x] +0.05 , data[y,x] + 0.05
                 horizontalalignment='center',
                 verticalalignment='center',
                 color='w')

#plt.colorbar(heatmap)

plt.show()

添加的情节:(不同的颜色但同样的问题) enter image description here

最佳答案

此功能由 seaborn 提供包裹。它可以生成像

这样的 map

Example annotated heatmap

seaborn 的用法示例是

import seaborn as sns
sns.set()

# Load the example flights dataset and conver to long-form
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")

# Draw a heatmap with the numeric values in each cell
sns.heatmap(flights, annot=True, fmt="d", linewidths=.5)

关于python - 使用 Pandas 数据框中的值注释热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21024066/

相关文章:

python - 如何在 matplotlib 中调整 x 轴

python - 为什么我不能在 iPython 中使用 app.MainLoop()?

python - 如何从 Python 中的 RSS 提要获取 XML 属性和值?

python - 使用 vtkCamera 显式投影变换矩阵和 prop3D 可见性

c - 如何比较C中文本的字符?

css - 以他的 parent 为中心的文本

c - fprintf 练习工作但运行后 txt 无效

python - 是否可以使用 itertools 限制迭代次数并将迭代器项存储在列表中?

python - joblib.Parallel 通过卡在 Windows 上的 spyder 运行

python - 如何在不同的 pdb(pp) session 之间保存状态?