20 Matplotlib concepts with Before-and-After Examples
1. Creating Basic Plots (plt.plot) 📈
Boilerplate Code:
import matplotlib.pyplot as plt
Use Case: Create a basic line plot to visualize data trends. 📈
Goal: Plot your data points and connect them with a line to see how they evolve. 🎯
Sample Code:
# Create a basic line plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
# Show the plot
plt.show()
Before Example: has data but no way to visualize trends. 🤔
Data: [1, 2, 3, 4], [10, 20, 25, 30]
After Example: With plt.plot(), the data is now visualized as a line plot! 📈
Line Plot: [X-axis: 1-4, Y-axis: 10-30]
Challenge: 🌟 Try plotting multiple lines by calling plt.plot() multiple times before plt.show().
2. Adding Titles and Labels (plt.title, plt.xlabel, plt.ylabel) 🏷️
Boilerplate Code:
plt.title('My Plot')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
Use Case: Add a title and labels to your plot’s axes for clarity. 🏷️
Goal: Make your plots more informative by labeling the axes and adding a title. 🎯
Sample Code:
# Add title and labels to the plot
plt.title('My Line Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
# Plot the data
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.show()
Before Example: a plot but it lacks context. 🤷♂️
Plot: no title, no axis labels.
After Example: With title and labels, the plot is now informative and easy to understand! 🏷️
Title: 'My Line Plot'
X Axis: 'X Axis'
Y Axis: 'Y Axis'
Challenge: 🌟 Try experimenting with different fonts and sizes for titles and labels using parameters like fontsize=14.
3. Changing Line Styles (plt.plot with linestyle) 🎨
Boilerplate Code:
plt.plot(x, y, linestyle='--')
Use Case: Customize the line style (solid, dashed, dotted) in your plots for better distinction. 🎨
Goal: Make your plots more visually engaging and easier to read by changing the line style. 🎯
Sample Code:
# Create a dashed line plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30], linestyle='--')
# Show the plot
plt.show()
Before Example: plot uses default lines, which may not stand out. 😐
Line style: solid.
After Example: With linestyle='--', the plot now has a dashed line for better visibility! 🎨
Dashed Line Plot: [X: 1-4, Y: 10-30]
Challenge: 🌟 Try combining different styles like '-.' or ':' for other plots.
4. Adjusting Colors (plt.plot with color) 🎨
Boilerplate Code:
plt.plot(x, y, color='red')
Use Case: Customize the line color in your plot to make it visually distinct. 🎨
Goal: Change the line color to enhance plot readability or match a theme. 🎯
Sample Code:
# Create a red line plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30], color='red')
# Show the plot
plt.show()
Before Example: plot uses the default blue color, which may not stand out. 🤷♂️
Line color: blue (default).
After Example: With color='red', the plot now uses a distinct, bright color! 🎨
Red Line Plot: [X: 1-4, Y: 10-30]
Challenge: 🌟 Try using different colors like green, orange, or even hex codes like #ff5733.
5. Scatter Plots (plt.scatter) 🔵
Boilerplate Code:
plt.scatter(x, y)
Use Case: Create a scatter plot to visualize relationships between two variables. 🔵
Goal: Plot individual data points to explore correlations or clusters. 🎯
Sample Code:
# Create a scatter plot
plt.scatter([1, 2, 3, 4], [10, 20, 25, 30])
# Show the plot
plt.show()
Before Example: want to visualize individual data points but doesn’t know how. 🤔
Data: scattered points [X: 1-4, Y: 10-30].
After Example: With plt.scatter(), the data is now displayed as a scatter plot! 🔵
Scatter Plot: individual points at [X: 1-4, Y: 10-30].
Challenge: 🌟 Try customizing the size and color of the scatter points using parameters like s=100, c='red'.
6. Bar Charts (plt.bar) 📊
Boilerplate Code:
plt.bar(x, height)
Use Case: Create a bar chart to compare values across categories. 📊
Goal: Visualize categorical data using vertical or horizontal bars. 🎯
Sample Code:
# Create a bar chart
plt.bar(['A', 'B', 'C', 'D'], [5, 7, 3, 8])
# Show the plot
plt.show()
Before Example: has categorical data but no visual comparison. 🤷
Categories: ['A', 'B', 'C', 'D'], Values: [5, 7, 3, 8]
After Example: With plt.bar(), the categories are visualized as bars! 📊
Bar Chart: ['A', 'B', 'C', 'D'] with heights [5, 7, 3, 8].
Challenge: 🌟 Try creating a horizontal bar chart using plt.barh() and see how it changes the visualization.
7. Histograms (plt.hist) 📉
Boilerplate Code:
plt.hist(data, bins=10)
Use Case: Create a histogram to visualize the distribution of data. 📉
Goal: Show the frequency of different values or ranges in your dataset. 🎯
Sample Code:
# Create a histogram with 10 bins
plt.hist([1, 1, 2, 2, 2, 3, 4, 5], bins=5)
# Show the plot
plt.show()
Before Example: has a dataset but can’t see its distribution. 🤔
Data: [1, 1, 2, 2, 2, 3, 4, 5]
After Example: With plt.hist(), the data distribution is clearly visible as a histogram! 📉
Histogram: data grouped into 5 bins.
Challenge: 🌟 Try adjusting the number of bins to see how it affects the histogram.
8. Subplots (plt.subplot, plt.subplots) 📊📊
Boilerplate Code:
plt.subplot(1, 2, 1)
plt.subplot(1, 2, 2)
Use Case: Create subplots to display multiple plots side by side or in a grid. 📊📊
Goal: Visualize different aspects of your data in a single figure. 🎯
Sample Code:
# Create two subplots in a 1x2 grid
plt.subplot(1, 2, 1)
plt.plot([1, 2, 3], [4, 5, 6])
plt.subplot(1, 2, 2)
plt.bar([1, 2, 3], [7, 8, 9])
plt.show()
Before Example: need to compare different plots but can’t do so in one figure. 🤔
Plot 1: Line plot, Plot 2: Bar chart (separate).
After Example: With plt.subplot(), both plots are displayed side by side! 📊📊
Two Subplots: Line plot and bar chart.
Challenge: 🌟 Try creating a 2x2 grid of subplots and experiment with different plot types.
9. Logarithmic Scales (plt.xscale, plt.yscale) 📐
Boilerplate Code:
plt.xscale('log')
plt.yscale('log')
Use Case: Apply logarithmic scales to axes to better visualize data with large ranges. 📐
Goal: Handle data that spans several orders of magnitude more effectively. 🎯
Sample Code:
# Apply log scale to the x-axis
plt.plot([1, 10, 100], [10, 100, 1000])
plt.xscale('log')
plt.show()
Before Example: data has a wide range, making it hard to visualize on a linear scale. 😬
X values: [1, 10, 100], Y values: [10, 100, 1000]
After Example: With log scales, the plot is more readable! 📐
Logarithmic X-Axis: [1, 10, 100] plotted on log scale.
Challenge: 🌟 Try applying log scales to both axes (plt.yscale('log')) and see the difference.
10. Saving Figures (plt.savefig) 💾
Boilerplate Code:
plt.savefig('my_plot.png')
Use Case: Save your plot to a file (e.g., PNG, PDF) for reports or sharing. 💾
Goal: Export your plots to files for later use. 🎯
Sample Code:
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
# Save the plot to a file
plt.savefig('my_plot.png')
# The plot is saved as 'my_plot.png'!
Before Example: create plots but doesn’t know how to save them. 🤷♂️
Plot created but not saved.
After Example: With plt.savefig(), the plot is saved to a file! 💾
Saved plot as 'my_plot.png'.
Challenge: 🌟 Try saving the plot in different formats like PDF using plt.savefig('my_plot.pdf').
11. Figure Size and DPI (plt.figure) 📏
Boilerplate Code:
plt.figure(figsize=(8, 6), dpi=100)
Use Case: Customize the figure size and DPI (dots per inch) to adjust plot dimensions and resolution. 📏
Goal: Control the size and clarity of your plots for presentations or reports. 🎯
Sample Code:
# Set figure size and DPI
plt.figure(figsize=(8, 6), dpi=100)
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
# Show the plot
plt.show()
Before Example: plots are too small or too large for their report. 😕
Plot: small, not clear enough for print.
After Example: With figure size and DPI, the plot is perfectly sized and clear! 📏
Plot size: 8x6 inches, DPI: 100 (high resolution).
Challenge: 🌟 Try creating larger figures for presentations (figsize=(12, 8)) or higher resolution for printing (dpi=300).
12. Legends (plt.legend) 🏷️
Boilerplate Code:
plt.legend(['Line 1', 'Line 2'])
Use Case: Add a legend to your plot to label different data series. 🏷️
Goal: Make your plot easier to interpret by showing which line or data point belongs to which label. 🎯
Sample Code:
# Create two line plots
plt.plot([1, 2, 3], [4, 5, 6], label='Line 1')
plt.plot([1, 2, 3], [6, 5, 4], label='Line 2')
# Add legend
plt.legend()
# Show the plot
plt.show()
Before Example: plot has multiple lines but no explanation for what each line represents. 🤔
Plot: two lines but no labels.
After Example: With plt.legend(), the plot is now labeled and easy to understand! 🏷️
Legend: 'Line 1', 'Line 2'
Challenge: 🌟 Try positioning the legend in different locations using loc='upper right' or loc='lower left'.
13. Grid Lines (plt.grid) 📐
Boilerplate Code:
plt.grid(True)
Use Case: Add grid lines to your plot to improve readability by making it easier to interpret data points. 📐
Goal: Enable grid lines to help with aligning and reading values. 🎯
Sample Code:
# Create a plot with grid lines
plt.plot([1, 2, 3], [4, 5, 6])
# Add grid
plt.grid(True)
# Show the plot
plt.show()
Before Example: plot lacks grid lines, making it harder to read values. 🤔
Plot: no grid, hard to align data points.
After Example: With grid lines, it’s now much easier to align and interpret the data! 📐
Plot with grid lines for better readability.
Challenge: 🌟 Try changing the grid style with plt.grid(color='gray', linestyle='--').
14. Customizing Ticks (plt.xticks, plt.yticks) 🔢
Boilerplate Code:
plt.xticks([1, 2, 3], ['One', 'Two', 'Three'])
plt.yticks([4, 5, 6], ['Low', 'Medium', 'High'])
Use Case: Customize tick marks and labels on the x and y axes to make your plot more readable or fit specific requirements. 🔢
Goal: Change the values or labels of tick marks on the axes for better customization. 🎯
Sample Code:
# Create a plot with custom ticks
plt.plot([1, 2, 3], [4, 5, 6])
# Customize x and y axis tick labels
plt.xticks([1, 2, 3], ['One', 'Two', 'Three'])
plt.yticks([4, 5, 6], ['Low', 'Medium', 'High'])
# Show the plot
plt.show()
Before Example: plot uses default tick labels, which might not make sense in their context. 🤔
X-axis: [1, 2, 3], Y-axis: [4, 5, 6]
After Example: With custom tick labels, the plot is now more descriptive! 🔢
X-axis: ['One', 'Two', 'Three'], Y-axis: ['Low', 'Medium', 'High']
Challenge: 🌟 Try rotating the tick labels using plt.xticks(rotation=45).
15. Heatmaps (plt.imshow) 🌡️
Boilerplate Code:
plt.imshow(data, cmap='hot', interpolation='nearest')
Use Case: Create a heatmap to visualize the magnitude of values across a matrix or grid. 🌡️
Goal: Show a color-coded representation of data values, with different colors representing different magnitudes. 🎯
Sample Code:
# Create a 2D heatmap
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
plt.imshow(data, cmap='hot', interpolation='nearest')
# Show the heatmap
plt.show()
Before Example: has a matrix of numbers but no way to visualize it clearly. 🤔
Data: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
After Example: With plt.imshow(), the matrix is now visualized as a heatmap! 🌡️
Heatmap: color-coded values from 1 to 9.
Challenge: 🌟 Try using different color maps like cmap='cool' or cmap='viridis' to change the heatmap style.
16. Pie Charts (plt.pie) 🥧
Boilerplate Code:
plt.pie(data, labels=labels, autopct='%1.1f%%')
Use Case: Create a pie chart to represent categorical data as proportions of a whole. 🥧
Goal: Show how different categories contribute to the total. 🎯
Sample Code:
# Create a pie chart
data = [30, 20, 50]
labels = ['Category A', 'Category B', 'Category C']
plt.pie(data, labels=labels, autopct='%1.1f%%')
# Show the pie chart
plt.show()
Before Example: has categorical data but no way to show proportions. 🤷♂️
Data: [30%, 20%, 50%]
After Example: With plt.pie(), the data is now visualized as a pie chart! 🥧
Pie Chart: Categories A, B, C with respective proportions.
Challenge: 🌟 Try adding a explode parameter to pull one slice away from the pie.
17. Error Bars (plt.errorbar) 📏
Boilerplate Code:
plt.errorbar(x, y, yerr=0.2, fmt='o')
Use Case: Add error bars to your plot to represent uncertainty or variability in your data. 📏
Goal: Show the potential range of error for each data point. 🎯
Sample Code:
# Create a plot with error bars
plt.errorbar([1, 2, 3], [4, 5, 6], yerr=0.2, fmt='o')
# Show the plot
plt.show()
Before Example: has data with variability but no way to show the error range. 🤔
Data points: [1, 2, 3] with errors.
After Example: With error bars, the variability is now clearly represented! 📏
Error Bars: Data points with ±0.2 error range.
Challenge: 🌟 Try adding both yerr and xerr to show error bars on both axes.
18. 3D Plots (plt.figure with 3D projection) 🌍
Boilerplate Code:
from mpl_toolkits.mplot3d import Axes3D
Use Case: Create 3D plots
to visualize data with three dimensions. 🌍
Goal: Add a third axis (z-axis) to visualize multi-dimensional data. 🎯
Sample Code:
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter([1, 2, 3], [4, 5, 6], [7, 8, 9])
# Show the 3D plot
plt.show()
Before Example: has 3D data but is limited to 2D plots. 🤷♂️
Data: [X, Y, Z] but visualized in 2D.
After Example: With 3D plotting, the intern can now visualize all three dimensions! 🌍
3D Plot: Points in X, Y, Z space.
Challenge: 🌟 Try adding more points or experimenting with surface plots using ax.plot_surface().
19. Annotations (plt.annotate) 📝
Boilerplate Code:
plt.annotate('Annotation', xy=(x, y), xytext=(x+1, y+1),
arrowprops=dict(facecolor='black', arrowstyle='->'))
Use Case: Add annotations to your plot to highlight specific points or regions. 📝
Goal: Draw attention to important data points or trends with text and arrows. 🎯
Sample Code:
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])
# Add annotation
plt.annotate('Important point', xy=(2, 5), xytext=(3, 6),
arrowprops=dict(facecolor='black', arrowstyle='->'))
# Show the plot
plt.show()
Before Example: plot has interesting points, but they aren’t highlighted. 🤔
Plot: No annotations.
After Example: With annotations, the important point is clearly highlighted! 📝
Annotated point with arrow and label.
Challenge: 🌟 Try using different arrow styles or adding multiple annotations to highlight more points.
20. Twin Axes (plt.twinx) 🎯
Boilerplate Code:
ax1 = plt.gca()
ax2 = ax1.twinx()
Use Case: Create twin axes to plot two different sets of data with different y-axes on the same plot. 🎯
Goal: Visualize two related datasets on the same plot but with different scales. 🎯
Sample Code:
# Create a line plot with twin axes
fig, ax1 = plt.subplots()
ax1.plot([1, 2, 3], [4, 5, 6], 'g-')
ax1.set_ylabel('Y1 axis', color='g')
ax2 = ax1.twinx()
ax2.plot([1, 2, 3], [10, 20, 30], 'b-')
ax2.set_ylabel('Y2 axis', color='b')
# Show the plot
plt.show()
Before Example: Has two datasets but struggles to visualize them on the same plot due to different scales. 🤷♂️
Dataset 1: Y values [4, 5, 6], Dataset 2: Y values [10, 20, 30]
After Example: With twin axes, both datasets are plotted together with their respective y-axes! 🎯
Twin Axes: Two y-axes for two different datasets.
Challenge: 🌟 Try changing one axis to a logarithmic scale using ax2.set_yscale('log').