Matplotlib Tutorial — Basic Plotting with Python
DodaTech
2 min read
In this tutorial, you'll learn about Matplotlib Tutorial. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
What You'll Learn
Create various plots with Matplotlib — line plots, bar charts, scatter plots, histograms, customize colors and labels, and save figures for reports.
Why It Matters
Visualization is how you communicate data insights. Matplotlib is the most widely used Python plotting library and the foundation for Seaborn and pandas plotting.
Real-World Use
Plotting sales trends over time, comparing revenue across product categories, visualizing the distribution of customer ages, or creating a scatter plot of price vs. rating.
Basic Line Plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, label="sin(x)", color="blue", linewidth=2)
plt.title("Sine Wave")
plt.xlabel("X values")
plt.ylabel("sin(x)")
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Multiple Lines
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.cos(x)
plt.figure(figsize=(12, 6))
plt.plot(x, y1, label="sin(x)", linestyle="-", color="#e74c3c")
plt.plot(x, y2, label="cos(x)", linestyle="--", color="#3498db")
plt.plot(x, y3, label="sin(x)cos(x)", linestyle=":", color="#2ecc71")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Trigonometric Functions")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
Bar Chart
categories = ["Electronics", "Clothing", "Food", "Books", "Sports"]
revenue = [45000, 32000, 28000, 15000, 22000]
plt.figure(figsize=(10, 6))
bars = plt.bar(categories, revenue, color=["#3498db", "#e74c3c", "#2ecc71", "#f39c12", "#9b59b6"])
plt.title("Revenue by Product Category")
plt.xlabel("Category")
plt.ylabel("Revenue ($)")
plt.xticks(rotation=45)
# Add value labels on bars
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f"${height:,.0f}", ha="center", va="bottom")
plt.tight_layout()
plt.show()
Horizontal Bar
plt.figure(figsize=(10, 6))
plt.barh(categories, revenue, color="#3498db")
plt.xlabel("Revenue ($)")
plt.title("Revenue by Category (Horizontal)")
plt.tight_layout()
plt.show()
Scatter Plot
np.random.seed(42)
n = 200
x = np.random.randn(n) * 10
y = 2 * x + np.random.randn(n) * 5
sizes = np.random.randint(20, 200, n)
colors = np.random.randn(n)
plt.figure(figsize=(10, 8))
scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.6, cmap="viridis")
plt.colorbar(scatter, label="Color Value")
plt.xlabel("Feature X")
plt.ylabel("Feature Y")
plt.title("Scatter Plot with Size and Color Encoding")
plt.grid(alpha=0.3)
plt.show()
Histogram
data = np.random.randn(1000)
plt.figure(figsize=(10, 6))
plt.hist(data, bins=30, alpha=0.7, color="#3498db", edgecolor="white")
plt.axvline(data.mean(), color="red", linestyle="--", label=f"Mean: {data.mean():.2f}")
plt.axvline(data.median(), color="green", linestyle=":", label=f"Median: {data.median():.2f}")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Distribution of Data")
plt.legend()
plt.show()
Subplots
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Line plot
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title("Sine Wave")
# Bar chart
axes[0, 1].bar(categories[:4], revenue[:4])
axes[0, 1].set_title("Revenue")
axes[0, 1].tick_params(axis="x", rotation=45)
# Scatter
axes[1, 0].scatter(x[:50], y[:50], alpha=0.6)
axes[1, 0].set_title("Scatter")
# Histogram
axes[1, 1].hist(data, bins=20, alpha=0.7)
axes[1, 1].set_title("Distribution")
plt.tight_layout()
plt.show()
Saving Figures
# Save as PNG
plt.savefig("my_plot.png", dpi=300, bbox_inches="tight")
# Save as PDF (vector format)
plt.savefig("my_plot.pdf", bbox_inches="tight")
# Save as SVG (editable)
plt.savefig("my_plot.svg", format="svg")
# Transparent background
plt.savefig("my_plot.png", transparent=True)
Customization Reference
# Colors
colors = ["#e74c3c", "#3498db", "#2ecc71", "#f39c12", "#9b59b6"]
# Line styles
linestyles = ["-", "--", ":", "-."]
# Marker styles
markers = ["o", "s", "^", "D", "v", "*", "x"]
# Figure size
plt.figure(figsize=(10, 6))
# Grid
plt.grid(True, alpha=0.3, linestyle="--")
# Axis limits
plt.xlim(0, 10)
plt.ylim(-1.5, 1.5)
# Text
plt.text(5, 0.5, "Important point", fontsize=12)
# Annotations
plt.annotate("Peak", xy=(np.pi/2, 1), xytext=(np.pi/2, 1.5),
arrowprops=dict(facecolor="black", shrink=0.05))
Practice
- Load a dataset and create a line plot of a time series
- Create a bar chart comparing categorical values
- Make a scatter plot with color by category
- Create a 2×2 subplot layout
- Save the final figure as a high-resolution PNG
← Previous
NumPy Broadcasting Explained — Vectorized Operations
Next →
Seaborn Tutorial — Statistical Data Visualization
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro