Matplotlib Basics

Use the Template to explore the basics of Matplotlib. Create new cells with # %% as necessary.

Use the Plotting section, the Matplotlib Documentation, and the Matplotlib Cheetsheets for help.

Template
# %%
# Import matplotlib

import numpy as np  # For generating data

# %%
# Variables for plotting
x = np.linspace(0.001, 100, 1000)
y = np.log(x)

rng = np.random.RandomState()
a = rng.uniform(0, 1, 10)
b = rng.uniform(0, 1, 100)
c = rng.uniform(0, 1, 100)
d = rng.normal(0, 1, 100)

# %%
# Create a figure with a single axis (plotting area)
# and create a line plot for x and y [.plot]


# %%
# Create a figure with four axes (2 rows, 2 columns)
# Axis 1: Barplot of a (color green) (use np.arange for the X axis) [.bar]
# Axis 2: Scatter plot of b and c (marker x) [.scatter]
# Axis 3: Histogram of d (color red) [.hist]
# Axis 4: Boxplot of d [.boxplot]


# %%
# Set the figure title [.suptitle]
# Set the title of each axis/plot [.set_title]
# Fix the layout/spacing [.tight_layout]


# %%
# Save the figure
Solution
# %%
# Import matplotlib
import matplotlib.pyplot as plt
import numpy as np  # For generating data

# %%
# Variables for plotting
x = np.linspace(0.001, 100, 1000)
y = np.log(x)

rng = np.random.RandomState()
a = rng.uniform(0, 1, 10)
b = rng.uniform(0, 1, 100)
c = rng.uniform(0, 1, 100)
d = rng.normal(0, 1, 100)

# %%
# Create a figure with a single axis (plotting area)
# and create a line plot for x and y [.plot]
fig, ax = plt.subplots()
ax.plot(x, y)

# If you are not using Python Interactive mode or a Jupyter Notebook,
# you need to show the figure with fig.show()

# %%
# Create a figure with four axes (2 rows, 2 columns)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

# Axis 1: Barplot of a (color green) (use np.arange for the X axis) [.bar]
ax1.bar(np.arange(a.shape[0]), a, color="green")

# Axis 2: Scatter plot of b and c (marker x) [.scatter]
ax2.scatter(b, c, marker="x")

# Axis 3: Histogram of d (color red) [.hist]
ax3.hist(d, color="red")

# Axis 4: Boxplot of d [.boxplot]
ax4.boxplot(d)

# %%
# Set the figure title [.suptitle]
fig.suptitle("My First Figure")

# Set the title of each axis/plot [.set_title]
ax1.set_title("Bar Plot")
ax2.set_title("Scatter Plot")
ax3.set_title("Histogram")
ax4.set_title("Box Plot")

# Fix the layout/spacing [.tight_layout]
fig.tight_layout()

fig  # Or fig.show() if not in Interactive Mode/Notebook

# %%
# Save the figure
fig.savefig("my-first-figure.png")

My First Figure