Okay, let's put the concepts from this chapter into practice. We'll create a simple line plot and a scatter plot, applying the customization techniques you've learned. This hands-on exercise will help solidify your understanding of Matplotlib's fundamental plotting workflow.
First, ensure you have Matplotlib and NumPy imported. We'll use NumPy to generate some sample data for our plots.
import matplotlib.pyplot as plt
import numpy as np
Imagine we want to visualize the trend of a simple quadratic function, say y=x2, over a specific range.
Generate Data: Let's create some x values and calculate the corresponding y values.
# Generate x values from -5 to 5
x_line = np.linspace(-5, 5, 100)
# Calculate y values (y = x^2)
y_line = x_line**2
Create the Plot: Use plt.plot()
to create the line plot.
# Create a Figure and an Axes object
fig, ax = plt.subplots()
# Plot the data
ax.plot(x_line, y_line)
# Display the plot
plt.show()
Running this will show a basic line plot of the parabola.
Add Labels and Title: Make the plot informative by adding a title and axis labels.
fig, ax = plt.subplots()
ax.plot(x_line, y_line)
# Add title and labels
ax.set_title("Quadratic Function: y = x^2")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values (x^2)")
plt.show()
Customize Appearance: Let's change the line to be red and dashed, and make it slightly thicker.
fig, ax = plt.subplots()
# Plot with customizations
ax.plot(x_line, y_line, color='#f03e3e', linestyle='--', linewidth=2) # Red dashed line
ax.set_title("Customized Quadratic Function: y = x^2")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values (x^2)")
plt.show()
Set Axis Limits: Focus the view on the positive x-axis values where x is between 0 and 4.
fig, ax = plt.subplots()
ax.plot(x_line, y_line, color='#f03e3e', linestyle='--', linewidth=2)
ax.set_title("Focused Quadratic Function: y = x^2")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values (x^2)")
# Set x and y axis limits
ax.set_xlim(0, 4)
ax.set_ylim(0, 16) # y goes up to 4^2 = 16
plt.show()
Here is the final code combining all steps:
import matplotlib.pyplot as plt
import numpy as np
# 1. Generate Data
x_line = np.linspace(-5, 5, 100)
y_line = x_line**2
# 2. Create Figure and Axes
fig, ax = plt.subplots()
# 3. Plot with Customizations
ax.plot(x_line, y_line, color='#f03e3e', linestyle='--', linewidth=2)
# 4. Add Title and Labels
ax.set_title("Focused Quadratic Function: y = x^2")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values (x^2)")
# 5. Set Axis Limits
ax.set_xlim(0, 4)
ax.set_ylim(0, 16)
# 6. Display the plot
plt.show()
This plot now clearly shows the y=x2 relationship for x between 0 and 4, with informative labels and distinct styling.
Line plot showing y=x2 for x from 0 to 4. The line is red and dashed.
Now, let's create a scatter plot to visualize the relationship between two sets of random, but somewhat correlated, data points.
Generate Data: We'll create two arrays, x_scatter
and y_scatter
. Let's make y_scatter
depend slightly on x_scatter
with some added randomness.
# Set a seed for reproducibility
np.random.seed(42)
# Generate 50 random x values
x_scatter = np.random.rand(50) * 10 # Values between 0 and 10
# Generate y values with some correlation and noise
y_scatter = x_scatter + np.random.randn(50) * 2 # y = x + random noise
Create the Plot: Use plt.scatter()
to plot the points.
fig, ax = plt.subplots()
# Create the scatter plot
ax.scatter(x_scatter, y_scatter)
plt.show()
This displays the raw scatter plot.
Add Labels and Title: Add context to the plot.
fig, ax = plt.subplots()
ax.scatter(x_scatter, y_scatter)
# Add title and labels
ax.set_title("Relationship between Two Variables")
ax.set_xlabel("Independent Variable (X)")
ax.set_ylabel("Dependent Variable (Y)")
plt.show()
Customize Appearance: Let's change the marker color to orange, increase the size, and perhaps make them slightly transparent using the alpha
parameter.
fig, ax = plt.subplots()
# Plot with customizations
ax.scatter(x_scatter, y_scatter, color='#fd7e14', s=50, alpha=0.7) # Orange, size 50, slightly transparent
ax.set_title("Customized Relationship between Two Variables")
ax.set_xlabel("Independent Variable (X)")
ax.set_ylabel("Dependent Variable (Y)")
plt.show()
Here is the final code for the scatter plot:
import matplotlib.pyplot as plt
import numpy as np
# 1. Generate Data
np.random.seed(42) # for reproducibility
x_scatter = np.random.rand(50) * 10
y_scatter = x_scatter + np.random.randn(50) * 2
# 2. Create Figure and Axes
fig, ax = plt.subplots()
# 3. Plot with Customizations
ax.scatter(x_scatter, y_scatter, color='#fd7e14', s=50, alpha=0.7) # Orange, size 50, alpha 0.7
# 4. Add Title and Labels
ax.set_title("Customized Relationship between Two Variables")
ax.set_xlabel("Independent Variable (X)")
ax.set_ylabel("Dependent Variable (Y)")
# 5. Display the plot
plt.show()
This scatter plot shows the individual data points representing the relationship between X and Y, styled for better visibility.
Scatter plot showing the relationship between two variables. Markers are orange, semi-transparent circles.
These exercises cover the core skills from this chapter: creating line and scatter plots, adding essential labels and titles, and customizing visual elements like color, line style, and marker properties. Experiment further by trying different functions for the line plot, adjusting the noise level in the scatter plot data, or exploring other color codes and line styles available in Matplotlib. The more you practice, the more comfortable you'll become with these fundamental tools.
© 2025 ApX Machine Learning