add legend to colorbar

Solutions on MaxInterview for add legend to colorbar by the best coders in the world

showing results for - "add legend to colorbar"
Audrey
01 Nov 2017
1import matplotlib.pyplot as plt
2import numpy as np
3from matplotlib.colors import ListedColormap
4
5#discrete color scheme
6cMap = ListedColormap(['white', 'green', 'blue','red'])
7
8#data
9np.random.seed(42)
10data = np.random.rand(4, 4)
11fig, ax = plt.subplots()
12heatmap = ax.pcolor(data, cmap=cMap)
13
14#legend
15cbar = plt.colorbar(heatmap)
16cbar.ax.set_yticklabels(['0','1','2','>3'])
17cbar.set_label('# of contacts', rotation=270)
18
19# put the major ticks at the middle of each cell
20ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
21ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
22ax.invert_yaxis()
23
24#labels
25column_labels = list('ABCD')
26row_labels = list('WXYZ')
27ax.set_xticklabels(column_labels, minor=False)
28ax.set_yticklabels(row_labels, minor=False)
29
30plt.show()