matplot imshow为每种颜色添加标签并将其放入图例

时间:2016-11-17 18:32:29

标签: python matplotlib label legend imshow

我想在matplotlib中显示如下图像(从here复制)

enter image description here

但我想标记每种颜色并将它们放在侧面的传奇上,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:6)

我认为在矩阵中为所有值设置图例只有在没有太多的情况下才有意义。因此,假设您的矩阵中有8个不同的值。然后我们可以为每个颜色创建一个相应颜色的代理艺术家,并将它们放入像这样的图例

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

# create some data
data = np.random.randint(0, 8, (5,5))
# get the unique values from data
# i.e. a sorted list of all values in data
values = np.unique(data.ravel())

plt.figure(figsize=(8,4))
im = plt.imshow(data, interpolation='none')

# get the colors of the values, according to the 
# colormap used by imshow
colors = [ im.cmap(im.norm(value)) for value in values]
# create a patch (proxy artist) for every color 
patches = [ mpatches.Patch(color=colors[i], label="Level {l}".format(l=values[i]) ) for i in range(len(values)) ]
# put those patched as legend-handles into the legend
plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0. )

plt.grid(True)
plt.show()

enter image description here