0

Code borrowed from matplotlib: colorbars and its text labels

I am working on a similar figure but I can't figure out how to change the font of "cbar.ax.text" to Arial.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#lebels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Possible duplicate of [How to change the font size on a matplotlib plot](https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot) – Luce May 30 '17 at 17:25
  • @Luce I tried but it changes the font of everything except for the labels of the cbar. – user8087767 May 30 '17 at 17:34

1 Answers1

0

The question I linked was not an exact duplicate (oops), but gives you an idea of how to edit the global font properties. Add the following lines to the top of you code:

font = {'family' : 'sans-serif',
        'sans-serif': 'Ariel'}

matplotlib.rc('font', **font)

See the documentation of matplotlib and this question: How to change the font size on a matplotlib plot.

Luce
  • 184
  • 2
  • 9
  • It doesn't change the font from the cbar to Arial. It does change the axis, but not the color bar. – user8087767 May 30 '17 at 17:42
  • If you remove the $ around the text labels, it does work. I.e. change: `for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):` to `for j, lab in enumerate(['0','1','2','>3']):` – Luce May 30 '17 at 18:44