Python plots with Matplotlib

  • Post author:
  • Post category:Python

Python code for two plots with figure and ax objects

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()
matplotlib02

Python code for two plots with plt methods

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()
matplotlib03

Python code for two plots in one figure with shared y axis

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.subplots_adjust(top=0.88)
figure.savefig("matplotlib04.pdf")
figure.show()
matplotlib04