Matplotlib: A Comprehensive Guide
Introduction
Matplotlib is a popular Python library for data visualization. It offers a variety of plots to visualize data
effectively and works seamlessly with libraries like NumPy and Pandas.
Installation
To install Matplotlib, use the following command:
pip install matplotlib
Basic Structure
To create a plot, you generally follow these steps:
1. Import the library:
import matplotlib.pyplot as plt
2. Create a plot:
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Common Plot Types
Line Plot
Used to visualize trends over time.
Example:
x = [1, 2, 3, 4]
y = [10, 15, 20, 25]
plt.plot(x, y, label='Growth', color='blue', linestyle='--')
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Line Plot Example')
plt.legend()
plt.show()
Bar Plot
Used for categorical data comparison.
categories = ['A', 'B', 'C']
values = [10, 15, 7]
plt.bar(categories, values, color='orange')
plt.title('Bar Plot')
plt.show()
Scatter Plot
Used for finding relationships between variables.
x = [1, 2, 3, 4]
y = [10, 14, 15, 18]
plt.scatter(x, y, color='red')
plt.title('Scatter Plot')
plt.show()
Pie Chart
Used for displaying proportions.
labels = ['A', 'B', 'C']
sizes = [20, 30, 50]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Pie Chart')
plt.show()
Matplotlib Examples with Outputs
Line Plot Example
x = [1, 2, 3, 4]
y = [10, 15, 20, 25]
plt.plot(x, y, label='Growth', color='blue')
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Line Plot')
plt.legend()
plt.show()
Output: A line connecting the points (1, 10), (2, 15), (3, 20), (4, 25).
Bar Plot Example
categories = ['A', 'B', 'C']
values = [10, 15, 7]
plt.bar(categories, values, color='orange')
plt.title('Bar Plot')
plt.show()
Output: Three bars labeled A, B, C with heights 10, 15, 7 respectively.
Scatter Plot Example
x = [1, 2, 3, 4]
y = [10, 14, 15, 18]
plt.scatter(x, y, color='red')
plt.title('Scatter Plot')
plt.show()
Output: Red points at coordinates (1, 10), (2, 14), (3, 15), (4, 18).
Pie Chart Example
labels = ['A', 'B', 'C']
sizes = [20, 30, 50]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Pie Chart')
plt.show()
Output: A pie chart with three segments labeled A (20%), B (30%), C (50%).