How to unbold colorbar labels in a heatmap

Viewed 1007

I have the following code which creates a heatmap:

import matplotlib.pyplot as plt
import seaborn as sns

# Load dataset from seaborn
flights = sns.load_dataset('flights')
flights = flights.pivot('month', 'year', 'passengers')

# Plot heatmap
fig1, ax1 = plt.subplots(figsize=(8,8))
ax = sns.heatmap(flights, annot=True, fmt='d', cbar_kws={'label': 'Passenger Numbers'})

# Rotate x-axis labels
ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45)

# Set font size for colorbar title
ax1.figure.axes[-1].yaxis.label.set_size(12)
# Set font size for colorbar labels
ax1.figure.axes[-1].tick_params(labelsize=10)

# Set font for x-axis labels
plt.xticks(fontsize=12, fontstyle='oblique')
# Set font for y-axis labels
plt.yticks(fontsize=12, fontstyle='oblique')

# Bold 'February' in y-axis
for label in ax.get_yticklabels():
    if label.get_text() == 'February':
        label.set_weight('bold')

plt.show()

The heatmap looks like this: heatmap

How do I unbold the colorbar labels (ie. the 600, 500, 400 values in the colorbar etc.) so that it is unbolded and similar to how the years (in the x-axis) and the months (in the y-axis, except for February) are displayed?

Many thanks in advance to anyone who knows this.

1 Answers

You could try to set the style in the firtsly, and then do the changes, you can try something like:

import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
#Create the style of the font 
font = {'family' : 'serif',
        'weight' : 'normal',
        'size'   : 10}         

matplotlib.rc('font', **font) #set the font style created
# Load dataset from seaborn
flights = sns.load_dataset('flights')
flights = flights.pivot('month', 'year', 'passengers')

# Plot heatmap
fig1, ax1 = plt.subplots(figsize=(8,8))
ax = sns.heatmap(flights, annot=True, fmt='d', cbar_kws={'label': 'Passenger Numbers'})

# Rotate x-axis labels
ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45)

# Set font size for colorbar title
ax1.figure.axes[-1].yaxis.label.set_size(12)
# Set font size for colorbar labels
ax1.figure.axes[-1].tick_params(labelsize=10)

# Set font for x-axis labels
plt.xticks(fontsize=12, fontstyle='oblique')
# Set font for y-axis labels
plt.yticks(fontsize=12, fontstyle='oblique')

# Bold 'February' in y-axis
for label in ax.get_yticklabels():
    if label.get_text() == 'February':
        label.set_weight('bold')

plt.show()

If that doesn't work, you can try to update params of the style, before styling the x,y axis. You can try this by adding plt.rcParams.update({'font.weight': 'normal'}) before the # Set font size for colorbar title. You can see the posible fonts here.

Related