3.2 Plots with Multiple Axes

Example 5 : CO\(_2\) Data

You will need the follwing files for the plot (Right click and choose to ‘Download’).

  1. CO\(_2\) over time
  2. Temperature over time
# Based on: https://www.r-bloggers.com/2018/11/charting-the-top-five-climate-data-sets-using-ggplot2/

from matplotlib import pyplot as plt
import pandas as pd

plt.style.use('ggplot')                                           # Lets plot in style

# Load in some real data

co2_df = pd.read_csv('co2_data.txt',
                     sep='\t', skiprows=21,
                     names=['depth', 'age_ice', 'age_air', 'co2'])

temp_df = pd.read_table('temperature_data.txt',
                        delim_whitespace=True, skiprows=60,
                        names=['depth', 'age_ice', 'deuterium', 'temp'])

# Lets start plotting
fig, (co2_ax, temp_ax) = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(10,4))

co2_ax.plot(co2_df['age_ice']/1000, co2_df['co2'])
temp_ax.plot(temp_df['age_ice']/1000, temp_df['temp'],color='#0077BB')

co2_ax.set_ylabel('CO$_2$ Concentration')
temp_ax.set_ylabel('Temperature (C)')
temp_ax.set_xlabel('Millennia before present')

for ax in [co2_ax, temp_ax]:
    ax.grid(alpha=.35)
    ax.set_xlim(0, 430)
# (0, 430)
# (0, 430)
plt.tight_layout()
plt.show()

Example 6 : 2 x 2

from matplotlib import pyplot as plt
import numpy as np

#--------- Generate cosine and sine values --------#
x = np.linspace(-np.pi, np.pi, num=100, endpoint=True)
cos_x = np.cos(x)
sin_x = np.sin(x)
fun_cos_x = np.exp(-x)*np.cos(5*x)
fun_sin_x = np.exp(-x)*np.sin(5*x)

#------------------ Plot the data -----------------#
fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(12, 8))

# Plot 0,0 : Cosines
ax[0, 0].plot(x, cos_x, color='r', label='cos x')
ax[0, 0].plot(x, cos_x**2, color='grey', linestyle='--', label='cos$^2$ x')
ax[0, 0].set_title('Cosine x & Cosine$^2$ x')
ax[0, 0].set_xlim(-np.pi, np.pi)
# (-3.141592653589793, 3.141592653589793)
ax[0, 0].legend(loc='lower center', frameon=False)

# Plot 0,1 : Sine
ax[0, 1].plot(x, sin_x, color='g', label='sin x')
ax[0, 1].plot(x, sin_x**2, color='grey', linestyle='--', label='sin$^2$ x')
ax[0, 1].set_title('Sin x & Sin$^2$ x')
ax[0, 1].set_ylim(-1.25, 1.25)
# (-1.25, 1.25)
ax[0, 1].legend(loc='lower right', frameon=False)

# Plot 1,0 : Function with Cosine
ax[1, 0].plot(x, fun_cos_x, color='r')
ax[1, 0].fill_between(x, fun_cos_x, 0, color='r', alpha=.125)
ax[1, 0].set_title('Function with Cosine')
ax[1, 0].set_xlim(-np.pi, np.pi)

# Plot 0,1 : Function with Sine
# (-3.141592653589793, 3.141592653589793)
ax[1, 1].plot(x, fun_sin_x, color='g')
ax[1, 1].fill_between(x, fun_sin_x, 0, color='g', alpha=.125)
ax[1, 1].set_title('Function with Sine')
ax[1, 1].set_xlim(-np.pi, np.pi)
# (-3.141592653589793, 3.141592653589793)
for a in ax.flat:            # 'flat', 'opens' the 2D list into a simple 1D list
    a.grid(alpha=.5)
    a.set_xlabel('Angle (radians)')
    a.set_xlim(-np.pi, np.pi)
# Text(0.5, 0, 'Angle (radians)')
# (-3.141592653589793, 3.141592653589793)
# Text(0.5, 0, 'Angle (radians)')
# (-3.141592653589793, 3.141592653589793)
# Text(0.5, 0, 'Angle (radians)')
# (-3.141592653589793, 3.141592653589793)
# Text(0.5, 0, 'Angle (radians)')
# (-3.141592653589793, 3.141592653589793)
for a in ax[0].flat:         # All the first row plots
    a.set_ylim(-1, 1)
# (-1, 1)
# (-1, 1)
for a in ax[1].flat:         # All the second row plots
    a.set_ylim(-20, 15)
# (-20, 15)
# (-20, 15)
plt.tight_layout()
plt.savefig('three-plots.png', dpi=300, transparent=True)
plt.show()