Introduction
Matplotlib is your best friend when it comes to visualizing data in Python. If Pandas is a data ninja, then Matplotlib is the artist that turns your boring numbers into stunning charts!
Installing Matplotlib
First, let’s install Matplotlib:
pip install matplotlib
Check if it’s installed correctly:
import matplotlib.pyplot as plt
print(plt.__version__)
Your First Plot
Let’s start with a simple line plot:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.plot(x, y, marker='o', linestyle='--', color='r', label='Sales')
plt.xlabel("Days")
plt.ylabel("Revenue ($)")
plt.title("Simple Line Chart")
plt.legend()
plt.show()
Boom! You’ve just created your first chart!
Bar Charts
Bar charts are great for comparing values.
categories = ["A", "B", "C", "D"]
values = [5, 7, 3, 8]
plt.bar(categories, values, color=['blue', 'green', 'red', 'purple'])
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Chart Example")
plt.show()
Scatter Plots
Perfect for showing relationships between variables.
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
plt.scatter(x, y, color='purple', marker='x')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Scatter Plot Example")
plt.show()
Pie Charts
Because who doesn’t love pie?
labels = ["Apple", "Banana", "Cherry", "Date"]
sizes = [30, 25, 20, 25]
colors = ["red", "yellow", "pink", "brown"]
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
plt.title("Pie Chart Example")
plt.show()
Histograms
Great for visualizing distributions.
data = np.random.randn(1000)
plt.hist(data, bins=30, color='skyblue', edgecolor='black')
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram Example")
plt.show()
Customizing Plots
Want to make your charts prettier? Here are some tweaks:
- Change colors
- Add grid lines
- Use different markers
plt.plot(x, y, color='green', linestyle='-.', marker='s', markersize=8)
plt.grid(True)
plt.show()
Summary
Feature | Matplotlib Advantage |
---|---|
Line Charts | Show trends easily |
Bar Charts | Compare categories visually |
Scatter Plots | Show relationships between data points |
Pie Charts | Visualize proportions |
Histograms | Understand distributions |
Matplotlib is the Michelangelo of Python data visualization. Now go and make your data look beautiful!
0 Comments