Editor

Build a Dual-Axis Temperature and Humidity Chart

Advanced · Write the code · from Advanced Matplotlib: Subplots, Dual Axes, Styles, Annotations

From the lesson: Advanced Matplotlib: Subplots, Dual Axes, Styles, Annotations

You know how to create a single chart. But real-world reports rarely have just one. A data analyst might need four charts side by side, each zoomed into a different slice of the same dataset.

Read the lesson

Create a chart with twin y-axes. Plot temperature on the left axis and humidity on the right axis using ax1.twinx(). Set the left y-label to 'Temperature (C)' and the right y-label to 'Humidity (%)'. Print both y-axis labels.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
hours = list(range(0, 24, 3)) # 0, 3, 6, ..., 21
temperature = [18, 16, 15, 20, 25, 28, 26, 22]
humidity = [80, 85, 88, 70, 55, 45, 50, 65]
# Create figure and primary axis
# Plot temperature on left axis
# Create twin axis and plot humidity
# Set labels and print them

More Matplotlib Subplots exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz