使用matplotlib在网格中显示值 [英] Show the values in the grid using matplotlib

查看:490
本文介绍了使用matplotlib在网格中显示值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为一些数据生成热图,我的代码如下所示:

I m trying to generate heatmaps for the some data and my code is shown below:

data = [['basis', 2007, 2008],
        [1, 2.2, 3.4],
        [2, 0, -2.2],
        [3, -4.1, -2.5],
        [4, -5.8, 1.2],
        [5, -5.4, -3.6],
        [6, 1.4, -5.9]]

x_header = data[0][1:]
y_header = [i for i in range(1, 13)]
data=data[1:]
for i in range(len(data)):
    data[i] = data[i][1:]
arr = np.array(data)
fig, ax = plt.subplots()
#heatmap = plt.pcolor(arr, cmap = 'RdBu')
norm = MidpointNormalize(midpoint=0)
im = ax.imshow(data, norm=norm, cmap=plt.cm.seismic, interpolation='none')

ax.set_xticks(np.arange(arr.shape[1]), minor=False)
ax.set_yticks(np.arange(arr.shape[0]), minor=False)
ax.xaxis.tick_top()
ax.set_xticklabels(x_header, rotation=90)
ax.set_yticklabels(y_header)

fig.colorbar(im)
plt.show()

它生成图像

我也想在网格内显示值.有什么办法吗?

I also want to show values inside the grid. Is there any way to do that?

推荐答案

当然,只需执行以下操作即可:

Sure, just do something like:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.random((4, 4))

fig, ax = plt.subplots()
# Using matshow here just because it sets the ticks up nicely. imshow is faster.
ax.matshow(data, cmap='seismic')

for (i, j), z in np.ndenumerate(data):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')

plt.show()

但是,标签很难看到,因此您可能需要在它们周围放置一个框:

However, the labels are hard to see, so you might want a box around them:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.random((4, 4))

fig, ax = plt.subplots()
# Using matshow here just because it sets the ticks up nicely. imshow is faster.
ax.matshow(data, cmap='seismic')

for (i, j), z in np.ndenumerate(data):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center',
            bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3'))

plt.show()

此外,在许多情况下,ax.annotateax.text更有用.在放置文本的方式上它要灵活得多,但也要复杂得多.在此处查看示例: http://matplotlib.org/users/annotations_guide.html

Also, in many cases, ax.annotate is more useful that ax.text. It's much more flexible in how you can position text, but it's also more complex. Have a look at the examples here: http://matplotlib.org/users/annotations_guide.html

这篇关于使用matplotlib在网格中显示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆