简体   繁体   中英

Plotting discrete colorbar in legend style using Matplotlib

Sometimes, I want to plot discrete value in pcolormesh style.

For example, to represent a 2-d array in the shape of 100x100 which contain int 0~7

data  = np.random.randint(8, size=(100,100))
cmap = plt.cm.get_cmap('PiYG', 8) 
plt.pcolormesh(data,cmap = cmap,alpha = 0.75)
plt.colorbar()  

The figure shows like this:
在此处输入图片说明

How to generate the colorbar in legend style. In other word, each color box corresponds to its value(eg pink colorbox --> 0)

An illustration here(Not fit this example):

在此处输入图片说明

Maybe the easiest way is to create corresponding number of Patch instances:

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

data  = np.random.randint(8, size=(100,100))
cmap = plt.cm.get_cmap('PiYG', 8) 
plt.pcolormesh(data,cmap = cmap,alpha = 0.75)
# Set borders in the interval [0, 1]
bound = np.linspace(0, 1, 9)
# Preparing borders for the legend
bound_prep = np.round(bound * 7, 2)
# Creating 8 Patch instances
plt.legend([mpatches.Patch(color=cmap(b)) for b in bound[:-1]],
           ['{} - {}'.format(bound_prep[i], bound_prep[i+1] - 0.01) for i in range(8)])

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM