Matplotlib is a powerful and versatile Python library for creating static, interactive, and publication-quality visualizations. It is widely used in data science, scientific research, engineering, finance, and many other fields for visualizing data and conveying insights.
With Matplotlib, we can create a wide range of plots, including line plots, scatter plots, bar plots, histograms, pie charts, heat maps, and more. Its flexibility and extensive customization options allow us to create visually appealing and informative plots tailored to our specific needs.
import matplotlib.pyplot as plt
Preparing one-dimensional data
import numpy as np# Method 1: Generate random datax = np.random.rand(100)y = np.random.rand(100)# Method 2: Generate data using a mathematical functionx = np.linspace(0, 2*np.pi, 100)y = np.sin(x)# Method 3: Load data from CSV filedata = pd.read_csv('data.csv')x = data['x']y = data['y']# Method 4: Manually create datax = [1, 2, 3, 4, 5]y = [5, 4, 3, 2, 1]# Method 5: Fetch data from an APIresponse = requests.get('https://api.example.com/data')data = response.json()# Extract x and y values from the API responsex = [point['x'] for point in data]y = [point['y'] for point in data]
Preparing two-dimensional data
import numpy as np# Method 1: Using a meshgrid# Define the range of x and y valuesx = np.linspace(-5, 5, 100)y = np.linspace(-5, 5, 100)# Create a meshgridX, Y = np.meshgrid(x, y)# Define a function to generate Z values (example: a saddle shape)Z = X**2 - Y**2# Method 2: Generate random matrixdata = np.random.rand(10, 10)# Method 3: Use image for datafrom PIL import Image# Load an imageimage = Image.open('image.jpg')# Convert image to numpy arraydata = np.array(image)
Create a basic plot
x_values = [0,1,2,3,4,5]y_values = [0,1,2,3,4,5]plt.plot(x_values, y_values)
Creating a line plot with a label and title
x_values = [0,1,2,3,4,5]y_values = [0,1,2,3,4,5]plt.plot(x_values, y_values, label='Data')plt.xlabel('X-axis')plt.ylabel('Y-axis')plt.title('Line plot example')plt.legend()
Creating a scatter plot
x_values = [0,1,2,3,4,5]y_values = [0,2,5,1,4,5]plt.scatter(x_values, y_values)plt.xlabel('X-axis')plt.ylabel('Y-axis')plt.title('Scatter plot example')plt.legend()
Creating a histogram
data = [10, 20, 30, 25, 15, 35, 40, 50, 45, 55, 60, 70, 80, 90, 95, 85, 100]plt.hist(data, bins = 5) # Create the histogram with 5 binsplt.xlabel('X-axis')plt.ylabel('Y-axis')plt.title('Histogram example')plt.legend()
Creating a bar plot
X_axis = ['A', 'B', 'C', 'D', 'E']Y_axis = [20, 35, 30, 25, 40]plt.bar(X_axis, Y_axis)plt.xlabel('X_axis')plt.ylabel('Y_axis')plt.title('Bar graph example')plt.show()
Creating a pie chart
sizes = [20, 30, 25, 15, 10] # Sizes of each slicelabels = ['A', 'B', 'C', 'D', 'E'] # Labels for each slice# Create the pie chartplt.figure(figsize=(6, 6)) # Set the figure sizeplt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=['skyblue', 'yellowgreen', 'orange', 'lightcoral', 'lightskyblue'])plt.title('Pie Chart Example')plt.show()
Creating a heatmap
data = [[random.random() for _ in range(10)] for _ in range(10)] # Random 10x10 matrixplt.figure(figsize=(8, 6)) # Set the figure sizeplt.imshow(data, cmap='viridis', interpolation='nearest')plt.colorbar() # Add colorbarplt.title('Heatmap Example')plt.xlabel('X-axis')plt.ylabel('Y-axis')plt.show()
The figure function with its defining parameters
# Create a new figure with specified parametersfig = plt.figure(num=1, # Figure numberfigsize=(8, 6), # Figure size (in inches)dpi=100, # Dots per inch (resolution)facecolor='lightblue', # Background coloredgecolor='red', # Border colorframeon=False, # Display frametight_layout={'pad': 2} # Adjust subplot parameters)# Add a subplotax = fig.add_subplot(111)ax.plot([1, 2, 3], [4, 5, 6])# Set title and labelsax.set_title('Line Plot')ax.set_xlabel('X-axis')ax.set_ylabel('Y-axis')# Show the plotplt.show()
Axes
Axes enable precise manual placement and customization of individual plots within a figure, like a grid of plots.
# Create a figure and axes using fig.add_axes()fig = plt.figure()ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # [left, bottom, width, height]# Plot something on the axesax.plot([1, 2, 3], [4, 5, 6])ax.set_title('Using fig.add_axes()')ax.set_xlabel('X-axis')ax.set_ylabel('Y-axis')# Create subplots using fig.add_subplot()fig = plt.figure()# Subplot 1ax1 = fig.add_subplot(221)ax1.plot([1, 2, 3], [4, 5, 6])ax1.set_title('Subplot 1')# Subplot 2ax3 = fig.add_subplot(212)ax3.plot([1, 2, 3], [4, 5, 6])ax3.set_title('Subplot 2')# Create subplots using plt.subplots()fig3, axes = plt.subplots(nrows=2, ncols=2)# Plot something on each subplotfor i in range(2):for j in range(2):axes[i, j].plot([1, 2, 3], [4, 5, 6])axes[i, j].set_title(f'Subplot {i+1}{j+1}')# Create subplots with a single row using plt.subplots()fig4, axes2 = plt.subplots(ncols=3)# Plot something on each subplotfor i in range(3):axes2[i].plot([1, 2, 3], [4, 5, 6])axes2[i].set_title(f'Subplot {i+1}')# Adjust layoutplt.tight_layout()# Show the plotsplt.show()
Customizing line style and colors
The different types of line styles available are '-', '--', '-.', ':'.
# Plot with custom line style and colorplt.plot([1, 2, 3], [4, 5, 6], linestyle='--', color='red', linewidth = 2, alpha = 0.5)plt.show()
Adding annotations and text
The different types of values for ha
(horizontal alignment) are left, center and right. The different types of values for va
(vertical alignment) are top, center and bottom.
plt.plot([1, 2, 3], [4, 5, 6])plt.text(2, 5, 'Annotation', fontsize=12, ha='center', va='bottom')plt.show()
Changing marker style and size
The different type of marker styles available are 'o', 's', '^', 'x'.
plt.plot([1, 2, 3], [4, 5, 6], marker='o', markersize=10, markerfacecolor='blue', markeredgewidth=2, markeredgecolor='red')plt.show()
Customizing axis limits and labels
plt.plot([1, 2, 3], [4, 5, 6])plt.xlim(0, 4)plt.ylim(3, 7)plt.xlabel('X-axis', fontsize=12)plt.ylabel('Y-axis', fontsize=12)plt.show()
Setting plot title and legends
The different values available for font weight are normal, bold and light. The different values for loc
are best, upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center and center.
plt.plot([1, 2, 3], [4, 5, 6], label='Data')plt.title('Customized Plot', fontsize=14, fontweight='bold', color='green')plt.legend(fontsize=12, loc='upper right')plt.show()
Changing figure size and resolution
plt.figure(figsize=(8, 6), dpi=100)plt.plot([1, 2, 3], [4, 5, 6])plt.show()
Customizing tick mark and grids
plt.plot([1, 2, 3], [4, 5, 6])plt.xticks([1, 2, 3], ['A', 'B', 'C'], fontsize=12)plt.yticks(fontsize=12)plt.grid(True, linestyle='--', linewidth=0.5)plt.show()
For 1D data
# Generate sample datax = np.linspace(0, 2*np.pi, 100)y = np.sin(x)# Create subplotsfig, axes = plt.subplots(2, 2)# Plot lines connecting pointslines = axes[0, 0].plot(x, y)# Scatter plot of unconnected pointsaxes[0, 0].scatter(x, y)# Plot vertical barsaxes[0, 0].bar([1, 2, 3], [3, 4, 5])# Plot horizontal barsaxes[1, 0].barh([0.5, 1, 2.5], [0, 1, 2])# Draw a horizontal lineaxes[1, 1].axhline(0.45)# Draw a vertical lineaxes[0, 1].axvline(0.65)# Fill the area under the curveaxes[0, 1].fill(x, y, color='blue')# Fill between the curve and the x-axisaxes[1, 1].fill_between(x, y, color='yellow')# Set a different title for the entire plotfig.suptitle('Exploring Matplotlib Plotting Methods', fontsize=16)plt.show()
For 2D data
# Generate sample 2D datadata = np.random.rand(10, 10)data1 = np.random.rand(10, 10)data2 = np.random.rand(10, 10)img = np.random.rand(10, 10)# Create subplotsfig, axes2 = plt.subplots(1, 3)# Display an imageim = axes2[0].imshow(img, cmap='viridis', interpolation='nearest', vmin=2, vmax=2)axes2[0].set_title('Image')# Plot pseudocolor plot of 2D arrayaxes2[1].pcolor(data2)axes2[1].set_title('Pseudocolor Plot')# Plot pseudocolor plot of 2D arrayaxes2[1].pcolormesh(data)axes2[1].set_title('Pcolormesh Plot')# Plot contours of 2D arrayCS = axes2[2].contour(data1)axes2[2].set_title('Contour Plot')# Plot filled contours of 2D arrayaxes2[2].contourf(data1)axes2[2].set_title('Filled Contour Plot')# Label the contour plotplt.clabel(CS, inline=True, fontsize=8)plt.title('Contour Plot with Labels')plt.show()
For vector patterns
# Sample dataX, Y = np.meshgrid(np.arange(-3, 3, 0.5), np.arange(-3, 3, 0.5))U = -1 - X**2 + YV = 1 + X - Y**2# Create subplotsfig, axes = plt.subplots(1, 3)# Add an arrow to illustrate a directionaxes[0].arrow(0, 0, 0.5, 0.5)axes[0].set_title('Directional Arrow')# Plot a 2D field illustrating streamlinesaxes[1].streamplot(X, Y, U, V)axes[1].set_title('Streamlines')# Plot a 2D field representing vector directionsaxes[2].quiver(X, Y, U, V)axes[2].set_title('Vector Field')plt.show()
plt.close() # Close current plot windowplt.close('MyPlotWindow') # Close specific plot window using its nameplt.close('all') # Close all plot windowsplt.clf() # Clear the figureplt.cla() # Clear an axisplt.savefig('plot.png', dpi=300) # Save plot as PNG file with 300 DPIplt.savefig('plot.png', transparent=True) # Save plot with a transparent backgroundplt.savefig('plot.png', figsize=(8, 6)) # Save plot with a custom size
Free Resources