I am creating a confusion matrix plot for my data. Next to the plot, I am placing a colorbar and want to change the font size of the colorbar tick labels. I search on the internet for a while but could not figure out how I can change the font size of the ticks of my colorbar since I am creating the colorbar using imshow
. This could be because creating the colorbar this way is not the usual way as done/suggested in most places on the web (e.g. here and here). So I need your help for this. Here's how I'm creating my plot and add the colorbar next to it:
data=np.array([[0.83, 0.6, 0.76],[0.59, 0.46, 0.52],[0.62, 0.58, 0.88]])
xTicksMajor, yTicksMajor = [0.5, 1.5, 2.5], [0.5, 1.5, 2.5]
xTicksMinor, yTicksMinor = [0, 1, 2], [0, 1, 2]
fig, ax = plt.subplots()
cmapProp = {'drawedges': True, 'boundaries': np.linspace(0, 1, 13, endpoint=True).round(2)}
m = ax.imshow(data, cmap=plt.cm.get_cmap('Oranges'))
m.set_clim(0, 1)
ax.figure.colorbar(m, ax=ax, **cmapProp)
ax.set_xticks(xTicksMajor)
ax.set_yticks(yTicksMajor)
ax.set_xticks(xTicksMinor, minor=True)
ax.set_yticks(yTicksMinor, minor=True)
ax.yaxis.grid(True, color='black', linestyle='-', linewidth=0.5)
ax.xaxis.grid(True, color='black', linestyle='-', linewidth=0.5)
thresh = data.max() / 1.4
for i, j in itertools.product(range(data.shape[0]), range(data.shape[1])):
ax.text(j, i, format(data[i, j], '.2f'),
horizontalalignment="center",
verticalalignment='center',
color="black" if data[i, j] > thresh else "dimgrey",
fontsize=26)
fig.savefig('temp.png', dpi=200)
plt.close()
I tried changing the font size of the ticks as follow:
cmapProp = {'drawedges': True, 'boundaries': np.linspace(0, 1, 13, endpoint=True).round(2), 'fontsize': 14}
But this gives me the following error:
TypeError: init() got an unexpected keyword argument 'fontsize'
I wonder, how can I change the font size of the tick labels next to the colorbar? Feel free to make suggestions like creating the colorbar in a different way so that it is easy to change the fontsize.
Also, the above code results in the plot show below:
How about this:
...
fig, ax = plt.subplots()
cmapProp = {'drawedges': True, 'boundaries': np.linspace(0, 1, 13, endpoint=True).round(2)}
m = ax.imshow(data, cmap=plt.cm.get_cmap('Oranges'))
m.set_clim(0, 1)
# And here try this:
cbar = ax.figure.colorbar(m, ax=ax, **cmapProp)
cbar.ax.tick_params(labelsize=25) # set your label size here
...
bold labels:
...
cbar = ax.figure.colorbar(m, ax=ax, **cmapProp)
cbar.ax.tick_params(labelsize=25)
for tick in cbar.ax.yaxis.get_major_ticks():
tick.label2.set_fontweight('bold')
...