Depending on the distribution of our data, a linear scale may not be the best way to fit in all useful data points in a figure. In this case, we may need to modify the scale of the axes into a log or symmetric log scale. In Matplotlib, this can be done by plt.xscale() and plt.yscale() before defining the axes, or by ax.set_xscale() and ax.set_yscale() after an axis is defined.
We do not need to change the scale of the entire axis. To display a part of the axis in linear scale, we adjust the linear threshold with the argument linthreshx or linthreshy. To obtain a smooth continuous line, we can also mask the non-positive numbers with the argument nonposx or nonposy.
The following code snippet is an example of the different axis scales. For a simpler illustration, we only change the scale in the y axis. Similar operations can be applied to the x axis:
import numpy as np
import matplotlib.pyplot as plt
# Prepare 100 evenly spaced numbers from -200 to 200
x = np.linspace(-1000, 1000, 100)
y = x * 2
# Setup subplot with 3 rows and 2 columns, with shared x-axis.
# More details about subplots will be discussed in Chapter 3.
f, axarr = plt.subplots(2,3, figsize=(8,6), sharex=True)
for i in range(2):
for j in range(3):
axarr[i,j].plot(x, y)
# Horizontal line (y=10)
axarr[i,j].scatter([0], [10])
# Linear scale
axarr[0,0].set_title('Linear scale')
# Log scale, mask non-positive numbers
axarr[0,1].set_title('Log scale, nonposy=mask')
axarr[0,1].set_yscale('log', nonposy='mask')
# Log scale, clip non-positive numbers
axarr[0,2].set_title('Log scale, nonposy=clip')
axarr[0,2].set_yscale('log', nonposy='clip')
# Symlog
axarr[1,0].set_title('Symlog scale')
axarr[1,0].set_yscale('symlog')
# Symlog scale, expand the linear range to -100,100 (default=None)
axarr[1,1].set_title('Symlog scale, linthreshy=100')
axarr[1,1].set_yscale('symlog', linthreshy=100)
# Symlog scale, expand the linear scale to 3 (default=1)
# The linear region is expanded, while the log region is compressed.
axarr[1,2].set_title('Symlog scale, linscaley=3')
axarr[1,2].set_yscale('symlog', linscaley=3)
plt.show()
Let's compare the results of each axis scale in the following figure: