Plotting two different quantities that share a common independent variable on the same graph can be a compelling way to compare and visualize data. Figure below shows an example of such a plot, where the blue curve is linked to the left blue y-axis and the red data points are linked to the right red y-axis.
The code below shows how this can be done using matplotlib using the function twinx().
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(7.5, 4.5))
xa = np.linspace(0.01, 6.0, 150)
ya = np.sin(np.pi * xa) / xa
ax1.plot(xa, ya, '-C0')
ax1.set_xlabel('x (micrometers)')
# Make y-axis label, ticks and numbers match line color.
ax1.set_ylabel('oscillate', color='C0')
ax1.tick_params('y', colors='C0')
ax2 = ax1.twinx() # use same x-axis for a 2nd (right) y-axis
xb = np.arange(0.3, 6.0, 0.3)
yb = np.exp(-xb * xb / 9.0)
ax2.plot(xb, yb, 'oC3')
ax2.set_ylabel('decay', color='C3') # axis label
ax2.tick_params('y', colors='C3') # ticks & numbers
fig.tight_layout()
fig.savefig('figures/twoAxes.pdf')
plt.show()
After plotting the first set of data using the axes ax1, calling twinx() instructs matplotlib to use the same x-axis for a second x-y set of data, which we set up with a new set of axes ax2. The set_ylabel
and tick_parameters functions are used to harmonize the colors of the y-axes with the different data sets. There is an equivalent function twiny() that allows two sets of data to share a common y-axis and then have separate (top and bottom) x-axes.
The code below shows how this can be done using matplotlib using the function twinx().
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(7.5, 4.5))
xa = np.linspace(0.01, 6.0, 150)
ya = np.sin(np.pi * xa) / xa
ax1.plot(xa, ya, '-C0')
ax1.set_xlabel('x (micrometers)')
# Make y-axis label, ticks and numbers match line color.
ax1.set_ylabel('oscillate', color='C0')
ax1.tick_params('y', colors='C0')
ax2 = ax1.twinx() # use same x-axis for a 2nd (right) y-axis
xb = np.arange(0.3, 6.0, 0.3)
yb = np.exp(-xb * xb / 9.0)
ax2.plot(xb, yb, 'oC3')
ax2.set_ylabel('decay', color='C3') # axis label
ax2.tick_params('y', colors='C3') # ticks & numbers
fig.tight_layout()
fig.savefig('figures/twoAxes.pdf')
plt.show()
After plotting the first set of data using the axes ax1, calling twinx() instructs matplotlib to use the same x-axis for a second x-y set of data, which we set up with a new set of axes ax2. The set_ylabel
and tick_parameters functions are used to harmonize the colors of the y-axes with the different data sets. There is an equivalent function twiny() that allows two sets of data to share a common y-axis and then have separate (top and bottom) x-axes.
0 comments:
Post a Comment