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