Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
enter image description here

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

An illustration here(Not fit this example):

enter image description here

like image 435
Han Zhengzu Avatar asked Jun 09 '16 13:06

Han Zhengzu


1 Answers

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)])

enter image description here

like image 142
Vadim Shkaberda Avatar answered Sep 30 '22 16:09

Vadim Shkaberda