Matplotlib Exercises Solutions
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
1. Create a figure with axes and plot x and y
# Data
x = np.arange(0, 10)
y = x * 2
# Create a figure and axes
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
# Plot data
ax.plot(x, y, label="y = 2x")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_title("Plot of X vs Y")
ax.legend()
plt.show()
2. Create a figure with two axes
# Data
z = x ** 2
# Create figure and axes
fig = plt.figure()
ax1 = fig.add_axes([0, 0, 1, 1]) # Main axes
ax2 = fig.add_axes([0.1, 0.6, 0.2, 0.2]) # Small axes
# Plot on main axes
ax1.plot(x, z, label="z = x^2")
ax1.set_xlabel("X Label")
ax1.set_ylabel("Z Label")
ax1.set_title("Main Axes")
ax1.legend()
# Plot on small axes
ax2.plot(x, z, label="Zoomed In")
ax2.set_xlim(1, 2)
ax2.set_ylim(0, 5)
ax2.set_title("Small Axes")
ax2.legend()
plt.show()
3. Use subplots and a loop to replicate the output
# Create subplots
fig, axes = plt.subplots(1, 2)
# Plot in a loop
for ax in axes:
ax.plot(x, y)
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_title("Subplot")
plt.show()
4. Use subplots to replicate the output
# Create subplots
fig, axes = plt.subplots(2, 1)
# Plot data
axes[0].plot(x, y, label="y = 2x")
axes[1].plot(x, z, label="z = x^2")
axes[0].set_title("First Plot")
axes[1].set_title("Second Plot")
# Add legends
axes[0].legend()
axes[1].legend()
plt.tight_layout()
plt.show()
5. Plot multiple datasets on one canvas
# Create figure
fig, ax = plt.subplots()
# Plot data
ax.plot(x, y, label="y = 2x")
ax.plot(x, z, label="z = x^2")
ax.plot(x, y, label="y = 2x again")
ax.legend()
plt.show()
6. Resize the plots
# Adjust figure size
fig, ax = plt.subplots(figsize=(3, 4))
ax.plot(x, y, label="y = 2x")
ax.legend()
plt.show()
7. Create a scatter plot
# Create scatter plot
fig, ax = plt.subplots()
ax.scatter(x, y, label="Scatter Plot")
ax.set_title("Scatter Example")
ax.legend()
plt.show()