matplotlib_cheetsheet
matplotlib_cheetsheet
Introduction to Matplotlib
What is Matplotlib?
Matplotlib is a plotting library for the Python programming language and its numerical mathematics
extension NumPy. It provides a wide variety of plots and charts for visualizing data.
re
Text Annotation
e
Y-axis label
H ax.annotate()
2
Markers
ylabel
ax.scatter
ax.set_ylabel
Axes
Axis fig.subplots
ax.set_ylabel
0.25 0.50 0.75 1.25 1.50 1.75 2.25 2.50 2.75 3.25 3.50 3.75
0 1 2 3 4
X-axis label
xlabel x Axis
ax.set_xlabel ax.xaxis
b
Prepare your data
Organize your data in a format that Matplotlib can use for plotting. This often involves using
NumPy arrays or Python lists.
For example:
# Data preparation: Creating two lists representing x and y values
x = np.array([1, 2, 3, 4, 5]) # Array representing x values
y = np.array([10, 15, 13, 18, 16]) # Array representing y values
Plots and Data Visualization
c
Create a plot(s)
Use Matplotlib functions to create different types of plots, such as line plots, bar plots, scatter
plots, histograms, etc.
For example, for a line plot:
• Using the pyplot interface:
plt.plot(x, y)
*Note:
fig: This represents the entire figure object, including the entire graphical representation, such as axes, labels, legends,
etc. It’s like the canvas on which our plots are drawn.
ax: This represents an individual subplot or axis within the larger figure. Think of it as a container for a specific plot or chart.
We can have multiple axes within a single figure, each representing a separate plot.
d
Customize the plot
Add labels, titles, legends, grid lines, colors, and other customizations to make the plot more
informative and visually appealing.
For example:
plt.xlabel('X-axis') ax.set_xlabel("X-axis")
plt.ylabel('Y-axis') ax.set_ylabel("Y-axis")
plt.title('Simple Line Plot')
Or ax.set_title("Simple Line Plot")
plt.grid(True) ax.grid(True)
e
Save and display the plot
Use plt.show() to display the plot on your screen. You can also save the plot to a file using
plt.savefig().
plt.show()
16
Y-axis
14
12
10
1 2 3 4 5
X-axis
f
Interact with the plot (Optional)
Matplotlib provides interactive features for exploring the plot, such as zooming, panning, and
saving specific parts of the plot.
Plots and Data Visualization
Basic Plotting
Line Plot
• Creating a simple line plot
plt.plot(x, y)
16
Y-axis
14
12
10
1 2 3 4 5
X-axis
For example:
#Setting marker 's' uses a square marker and ‘o’ uses a circle marker for the plot points
plt.plot(x,y1, linestyle='--', marker='s', color='red')
plt.plot(x,y2, linestyle='--', marker='o', color='skyblue')
Scatter Plot
• Creating a scatter plot
plt.scatter(x, y)
Scatter Plot
18
17
16
15
Y-axis
14
13
12
11
10
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
X-axis
17
16
15
Y-axis
14
13
12
11
10
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
X-axis
Bar Plot
• Creating a bar plot
plt.bar(x, height)
17.5
15.0
12.5
10.0
7.5
5.0
2.5
0.0
1 2 3 4 5
100
80
60
40
20
0
-2 -1 0 1 2
100
100
100
80
60
40
20
0
-4 -3 -2 -1 0 1 2 3
Pie Chart
• Creating a pie chart
sizes =[55, 30, 15]
plt.pie(sizes)
Advanced Plotting
Subplots
The subplots() function in Matplotlib creates a grid of subplots within a single figure, making it
easier to compare different datasets or visualize multiple aspects of the same data.
• Creating subplots
# Step 1: Create some sample data
x = np.linspace(0, 2*np.pi, 400)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.exp(x/2) # Exponential function
# Step 2: Create a figure and a grid of subplots with different sizes
fig, axs = plt.subplots(2, 2, figsize=(10, 8),
gridspec_kw={'width_ratios': [2, 1], 'height_ratios': [1, 2]})
# Step 3: Plot the first subplot in the first row
axs[0, 0].plot(x, y1, color='r')
axs[0, 0].set_title('Sine Function')
# Step 4: Plot the second subplot in the first row
axs[0, 1].plot(x, y2, color='g')
axs[0, 1].set_title('Cosine Function')
# Step 5: Plot the third subplot in the second row
axs[1, 0].plot(x, y3, color='b')
axs[1, 0].set_title('Exponential Function')
# Step 6: Remove the empty subplot in the second row and the second column
fig.delaxes(axs[1, 1])
# Step 7: Adjust the spacing between subplots
plt.tight_layout()
# Step 8: Add a main title to the entire figure
fig.suptitle('Grid of Trigonometric Functions with Different Sizes', fontsize=16, y=1.05)
1.0 1.0 20
0.5 0.5 15
0.0 0.0 10
-0.5 -0.5 5
-1.0 -1.0 0
0 1 2 3 4 5 6 0 2 4 6 0 1 2 3 4 5 6
Tips
• Adjusting subplot size: Use figsize to control the overall size of the figure and gridspec_kw to
adjust the relative sizes of the subplots.
Plots and Data Visualization
• Removing subplots: Use fig.delaxes(ax) to remove unwanted subplots.
• Spacing and titles: The plt.tight_layout helps to automatically adjust subplot parameters to give
specified padding, and fig.suptitle adds a main title to the figure.
10
6 Here
5
2
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
Rotating text:
plt.annotate('Here', xy=(3, 6), xytext=(3.5, 7),
arrowprops=dict(facecolor='black', arrowstyle='->'), rotation = 45)
10
7 e ”
Her
6 d “
t e
a
5
R ot
4
2
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
legend 1
legend 2
3D Plotting
# Generate random data
np.random.seed(42)
x = np.random.normal(size=300)
y = np.random.normal(size=300)
z = np.random.normal(size=300)
# Create a 3D scatter plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Scatter plot
scatter = ax.scatter(x, y, z, c=z, cmap='viridis')
Saving Plots
• Saving plots as image files (PNG, JPEG, etc.)
plt.savefig('plot.png')
Best Practices
• Choosing the right plot type for your data
◦ Consider the nature of your data and the message you want to convey.
• Using descriptive labels and titles
◦ Clearly label your axes and provide a descriptive title for your plot.
• Avoiding cluttered and confusing plots
◦ Use appropriate plot types and avoid overcrowding your plots with data points.
• Using color effectively in plots
◦ Use color to highlight important information and make your plots more visually appealing.
Plots and Data Visualization
Performance Tips
When working with Matplotlib, follow these tips for better performance: