Monday, October 19, 2020

Stack Abuse: Change Font Size in Matplotlib

Introduction

Matplotlib is one of the most widely used data visualization libraries in Python. Much of Matplotlib's popularity comes from its customization options - you can tweak just about any element from its hierarchy of objects.

In this tutorial, we'll take a look at how to change the font size in Matplotlib.

Change Font Size in Matplotlib

There are a few ways you can go about changing the size of fonts in Matplotlib. You can set the fontsize argument, change how Matplotlib treats fonts in general, or even changing the figure size.

Let's first create a simple plot that we'll want to change the size of fonts on:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
fig.suptitle('Sine and cosine waves')
plt.xlabel('Time')
plt.ylabel('Intensity')
leg = ax.legend()

plt.show()

matplotlib plot

Change Font Size using fontsize

Let's try out the simplest option. Every function that deals with text, such as suptitle(), xlabel() and all other textual functions accept an argument - fontsize.

Let's revisit the code from before and specify a fontsize for these elements:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
fig.suptitle('Sine and cosine waves', fontsize=20)
plt.xlabel('Time', fontsize=16)
plt.ylabel('Intensity', fontsize=16)
leg = ax.legend()

plt.show()

Here, we've set the fontsize for the suptitle as well as the labels for time and intensity. Running this code yields:

matplotlib fontsize argument

We can also change the size of the font in the legend by adding the prop argument and setting the font size there:

leg = ax.legend(prop={"size":16})

This will change the font size, which in this case also moves the legend to the bottom left so it doesn't overlap with the elements on the top right:

matplotlib change legend font size

However, while we can set each font size like this, if we have many textual elements, and just want a uniform, general size - this approach is repetitive.

In such cases, we can turn to setting the font size globally.

Change Font Size Globally

There are two ways we can set the font size globally. We'll want to set the font_size parameter to a new size. We can get to this parameter via rcParams['font.size'].

One way is to modify them directly:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

plt.rcParams['font.size'] = '16'

ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
plt.xlabel('Time')
plt.ylabel('Intensity')
fig.suptitle('Sine and cosine waves')
leg = ax.legend()

plt.show()

You have to set these before the plot() function call since if you try to apply them afterwards, no change will be made. This approach will change everything that's specified as a font by the font kwargs object.

However, when we run this code, it's obvious that the x and y ticks, nor the x and y labels didn't change in size:

matplotlib change font size rc params

Depending on the Matplotlib version you're running, you won't be able to change these with rc parameters. You'd use axes.labelsize and xtick.labelsize/ytick.labelsize for them respectively.

If setting these doesn't change the size of labels, you can use the set() function passing in a fontsize or use the set_fontsize() function:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(12, 6))

x = np.arange(0, 10, 0.1)
y = np.sin(x)
z = np.cos(x)

# Set general font size
plt.rcParams['font.size'] = '16'

# Set tick font size
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_fontsize(16)
        
ax.plot(y, color='blue', label='Sine wave')
ax.plot(z, color='black', label='Cosine wave')
plt.xlabel('Time', fontsize=16)
plt.ylabel('Intensity', fontsize=16)

fig.suptitle('Sine and cosine waves')
leg = ax.legend()

plt.show()

This results in:

matplotlib change font size xtick and label

Conclusion

In this tutorial, we've gone over several ways to change the size of fonts in Matplotlib.

If you're interested in Data Visualization and don't know where to start, make sure to check out our book on Data Visualization in Python.

Data Visualization in Python, a book for beginner to intermediate Python developers, will guide you through simple data manipulation with Pandas, cover core plotting libraries like Matplotlib and Seaborn, and show you how to take advantage of declarative and experimental libraries like Altair.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...