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(e.g 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)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With