Matplotlib Pyplot
matplotlib.pyplot (often called plt by convention) is a module within Matplotlib that provides a simple interface for creating plots. It is modeled after MATLAB’s plotting functionality, allowing you to generate a wide variety of 2D plots with minimal code.
Basic Workflow with Pyplot
- Prepare your data: Define the data points you want to plot.
- Call plotting functions: Use functions like
plt.plot()to generate the plot. - Customize the plot: You can add titles, labels, legends, gridlines, etc.
- Display or save the plot: Call
plt.show()to display the plot orplt.savefig()to save it as an image file.
Basic Example
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 40, 50]
# Create a simple line plot
plt.plot(x, y)
# Add labels and title
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Simple Line Plot')
# Display the plot
plt.show()
Key Pyplot Functions
plt.plot(): Creates line plots. It can take many arguments likex,y, colors, line styles, markers, etc.plt.plot(x, y, color='blue', linestyle='--', marker='o')plt.bar(): Creates bar charts for categorical data.categories = ['A', 'B', 'C'] values = [10, 20, 15] plt.bar(categories, values)plt.scatter(): Creates scatter plots for displaying individual data points.plt.scatter(x, y, color='red')plt.hist(): Plots histograms to display frequency distributions.data = [1, 1, 2, 2, 2, 3, 3, 4] plt.hist(data, bins=3)plt.pie(): Creates pie charts to visualize proportions.labels = ['A', 'B', 'C'] sizes = [30, 40, 30] plt.pie(sizes, labels=labels)
Customization
- Titles, labels, and legends:
plt.title(): Adds a title to the plot.plt.xlabel(),plt.ylabel(): Add labels to the x and y axes.plt.legend(): Displays a legend to label the data.
Example:
plt.plot(x, y, label='Line 1') plt.title("Title") plt.xlabel("X Axis") plt.ylabel("Y Axis") plt.legend() # Adds 'Line 1' to the legend - Grid: Adding a grid is straightforward using
plt.grid(True).plt.grid(True) - Ticks: Customize the ticks on axes with
plt.xticks()andplt.yticks().plt.xticks([1, 2, 3, 4, 5], ['A', 'B', 'C', 'D', 'E'])
Subplots
plt.subplot() allows you to create multiple plots within the same figure. This is useful when you want to compare multiple charts side by side.
plt.subplot(1, 2, 1) # 1 row, 2 columns, plot 1
plt.plot(x, y)
plt.subplot(1, 2, 2) # 1 row, 2 columns, plot 2
plt.bar(categories, values)
plt.show()
Example with Different Plot Types
import matplotlib.pyplot as plt
# Data for plots
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
categories = ['A', 'B', 'C', 'D']
values = [5, 7, 9, 4]
# Line Plot
plt.subplot(2, 2, 1) # 2x2 grid, 1st plot
plt.plot(x, y)
plt.title("Line Plot")
# Bar Plot
plt.subplot(2, 2, 2) # 2x2 grid, 2nd plot
plt.bar(categories, values)
plt.title("Bar Plot")
# Scatter Plot
plt.subplot(2, 2, 3) # 2x2 grid, 3rd plot
plt.scatter(x, y)
plt.title("Scatter Plot")
# Histogram
plt.subplot(2, 2, 4) # 2x2 grid, 4th plot
data = [1, 2, 2, 3, 3, 4]
plt.hist(data, bins=4)
plt.title("Histogram")
# Show all plots
plt.tight_layout() # Adjust spacing between subplots
plt.show()
Saving Plots
You can save your plots as images using plt.savefig():
plt.plot(x, y)
plt.savefig('plot.png') # Saves the plot as a PNG file
Advanced Customizations
- Figure Size: You can control the size of the figure by using
plt.figure().plt.figure(figsize=(8, 6)) - Logarithmic Scales: If your data spans several orders of magnitude, you can apply a logarithmic scale to an axis.
plt.yscale('log') - Annotations: Add text or labels to specific points in the plot.
plt.annotate('Point of interest', xy=(2, 15), xytext=(3, 20), arrowprops=dict(facecolor='black', shrink=0.05))
Summary
Matplotlib’s pyplot interface makes it very easy to create a wide variety of plots with a few lines of code. Its flexibility in customization allows you to control every element of the plot, making it a popular choice for creating publication-quality graphics.