You are currently viewing Python Plots with Matplotlib: Object Oriented Axes, Twin Scales, and NaN Gaps

Python Plots with Matplotlib: Object Oriented Axes, Twin Scales, and NaN Gaps

  • Post author:
  • Post published:
  • Post category:Python

Matplotlib offers two distinct interfaces: the quick stateful pyplot shortcut (plt) and the explicit object oriented Figure and Axes API (fig, ax). Using the object oriented pattern becomes essential whenever engineering telemetry requires stacked subplots, secondary y axes via twinx(), or clean handling of dropped sensor samples represented as numpy.nan values.

Interactive Matplotlib Figure, Axes & NaN-Gap Previewer
Python Plotting

Experiment with inserting np.nan gaps, masking start/end samples, or switching to a dual twin y layout (twinx()), and compare the live waveform with the corresponding Python code.

SUBPLOTS WITH EXPLICIT FIGURE AND AXES OBJECTS

Assigning each subplot to its own Axes reference (ax1, ax3) lets you independently configure grid lines, axis titles, and missing NaN intervals without losing track of which panel is active. Notice how numpy.nan automatically breaks the plotted line cleanly without interpolating falsely across dropouts.

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(2 * 2*np.pi * t)
t[41:60] = np.nan

figure = plt.figure()

ax1 = plt.subplot(211)
ax3 = plt.subplot(212)

ax1.plot(t, s, '-', lw=2)
ax1.set_xlabel('time (s)')
ax1.set_ylabel('voltage (mV)')
ax1.set_title('A sine wave with a gap of NaNs between 0.4 and 0.6')
ax1.grid(True)

t[0] = np.nan
t[-1] = np.nan
ax3.plot(t, s, '-', lw=2)
ax3.set_title('Also with NaN in first and last point')
ax3.set_xlabel('time (s)')
ax3.set_ylabel('more nans')
ax3.grid(True)

figure.tight_layout()
figure.savefig("matplotlib02.pdf")
figure.show()

STATEFUL PYPLOT INTERFACE EQUIVALENT

The imperative plt interface produces the same visual PDF output by implicitly applying subsequent calls to whichever subplot was created most recently.

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(2 * 2*np.pi * t)
t[41:60] = np.nan

plt.subplot(2, 1, 1)
plt.plot(t, s, '-', lw=2)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('A sine wave with a gap of NaNs between 0.4 and 0.6')
plt.grid(True)

plt.subplot(2, 1, 2)
t[0] = np.nan
t[-1] = np.nan
plt.plot(t, s, '-', lw=2)
plt.title('Also with NaN in first and last point')
plt.xlabel('time (s)')
plt.ylabel('more nans')
plt.grid(True)

plt.tight_layout()
plt.savefig("matplotlib03.pdf")
plt.show()

SHARED X AXES AND SECONDARY TWIN Y SCALES

Calling ax1.twinx() creates an overlay Axes sharing the horizontal time domain while hosting a separate scaled vertical axis on the right margin, while sharex links pan and zoom behavior vertically across panels.

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 1.0 + 0.01, 0.01)
s1 = np.cos(2 * 2*np.pi * t)
s2 = 1.5*np.sin(2 * 2*np.pi * t)
t[41:60] = np.nan

figure = plt.figure()
figure.suptitle('A sine wave with a gap of NaNs between 0.4 and 0.6')
ax1 = plt.subplot(211)
ax2 = ax1.twinx()
ax3 = plt.subplot(212, sharex=ax1)
ax4 = ax3.twinx()

color1 = 'tab:red'
ax1.plot(t, s1, '-', lw=2, color=color1)
ax1.set_xlabel('time (s)')
ax1.set_ylabel('voltage (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
ax1.grid(True)

color2 = 'tab:blue'
ax2.plot(t, s2, '-', lw=2, color=color2)
ax2.set_xlabel('time (s)')
ax2.set_ylabel('voltage (mV)', color=color2)
ax2.set_title('First Title')
ax2.tick_params(axis='y', labelcolor=color2)
ax2.grid(True)

t[0] = np.nan
t[-1] = np.nan
ax3.plot(t, s1, '-', lw=2)
ax3.set_title('Second Title')
ax3.set_xlabel('time (s)')
ax3.set_ylabel('more nans')
ax3.grid(True)

figure.tight_layout()
figure.savefig("matplotlib04.pdf")
figure.show()