Matplotlib Tutorial for Beginners
Matplotlib is a popular data visualization library for Python that provides a wide range of tools for creating various types of plots and charts. In this tutorial, we'll cover 15 key concepts of Matplotlib to help you get started with creating compelling visualizations.
1. Installation and Import
To begin, install Matplotlib using pip:
bash
pip install matplotlib
Import the library in your Python script:
import matplotlib.pyplot as plt
2. Basic Line Plot
Create a simple line plot to visualize data:
x = [1, 2, 3, 4, 5]
y = [10, 25, 18, 30, 15]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Basic Line Plot')
plt.show()
3. Customizing Plots
Customize plot appearance using various options:
plt.plot(x, y, color='red', linestyle='dashed', marker='o', markersize=8, label='Data Points')
plt.legend()
plt.grid(True)
4. Multiple Subplots
Create multiple subplots in a single figure:
plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.subplot(2, 1, 2)
plt.scatter(x, y)
5. Scatter Plot
Generate a scatter plot to display individual data points:
plt.scatter(x, y, color='blue', marker='x', label='Scatter Points')
plt.legend()
6. Bar Plot
Visualize categorical data using bar plots:
categories = ['A', 'B', 'C', 'D']
values = [15, 30, 10, 25]
plt.bar(categories, values, color='green')
7. Histogram
Create a histogram to visualize data distribution:
data = [12, 15, 20, 22, 25, 30, 32, 35, 40, 45]
plt.hist(data, bins=5, color='orange', edgecolor='black')
8. Pie Chart
Display proportions with a pie chart:
labels = ['Apples', 'Bananas', 'Grapes', 'Oranges']
sizes = [35, 20, 25, 20]
plt.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['red', 'yellow', 'purple', 'orange'])
9. Box Plot
Create a box plot to visualize data spread and outliers:
data = [10, 15, 18, 22, 25, 30, 32, 35, 40, 45]
plt.boxplot(data)
10. Heatmap
Generate a heatmap to visualize a matrix of values:
import numpy as np
data = np.random.rand(5, 5)
plt.imshow(data, cmap='viridis')
plt.colorbar()
11. 3D Plotting
Create 3D plots for visualizing 3D data:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
12. Error Bars
Add error bars to visualize uncertainty in data points:
x = [1, 2, 3, 4, 5]
y = [10, 25, 18, 30, 15]
error = [2, 3, 1, 4, 2]
plt.errorbar(x, y, yerr=error, fmt='o', capsize=5)
13. Annotations and Text
Add annotations and text to enhance plot readability:
plt.plot(x, y)
plt.annotate('Max Value', xy=(4, 30), xytext=(3, 27),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.text(1, 12, 'Start', fontsize=12)
14. Saving and Exporting
Save plots as image files:
plt.plot(x, y)
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
15. Advanced Customization
Explore advanced customization options for fonts, colors, and styles:
plt.plot(x, y, color='red', linestyle='dashed', linewidth=2, label='Data')
plt.xlabel('X-axis', fontsize=14, color='blue')
plt.ylabel('Y-axis', fontsize=14, color='green')
plt.title('Advanced Customization', fontsize=16, fontweight='bold')
plt.legend(loc='upper right', fontsize=12)
plt.xticks(fontsize=10, rotation=45)
plt.yticks(fontsize=10)
plt.tight_layout()
plt.show()