ch13s2_MatplotlibForBasicPlots

[Matplotlib](https://matplotlib.org) is the **foundation of Python’s visualization ecosystem**, enabling you to create everything from quick line charts to highly customized figures.

Chapter 13: Data Visualization — Matplotlib for Basic Plots

🎨 Matplotlib for Basic Plots

Matplotlib is the foundation of Python’s visualization ecosystem, enabling you to create everything from quick line charts to highly customized figures.
It offers fine-grained control over every visual element — perfect for scientific, analytical, or publication-quality plots.


⚙️ 1. Installing Matplotlib

If not already installed, run:

pip install matplotlib

🧩 2. The Matplotlib Object Model

Matplotlib organizes visuals into three main components:

ComponentDescription
FigureThe overall window or page holding one or more plots
AxesThe actual plot or graph (where data lives)
AxisX and Y coordinate systems within the Axes
import matplotlib.pyplot as plt

fig, ax = plt.subplots()  # Create a figure with one Axes
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
ax.set_title("Basic Plot")
plt.show()

🎓 Use plt.subplots() instead of global plt.plot() for better structure and flexibility.


Line charts are ideal for tracking changes over time or continuous variables.

import matplotlib.pyplot as plt

years = [2018, 2019, 2020, 2021, 2022]
values = [100, 150, 130, 180, 210]

plt.figure(figsize=(8, 5))
plt.plot(years, values, marker='o', color='royalblue', linewidth=2, label="Growth")

plt.title("Yearly Values Over Time", fontsize=14, weight='bold')
plt.xlabel("Year")
plt.ylabel("Value")
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.tight_layout()
plt.show()

💡 Tip: Use plt.style.use('seaborn-v0_8-darkgrid') for cleaner defaults.


📊 4. Bar Charts — Comparing Categories

Bar charts are used to compare discrete groups or categories.

import matplotlib.pyplot as plt

categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 50]

plt.bar(categories, values, color='teal', alpha=0.8)
plt.title("Bar Chart Example", fontsize=14)
plt.xlabel("Category")
plt.ylabel("Value")
plt.grid(axis='y', linestyle='--', alpha=0.5)
plt.show()

Horizontal Bar Chart

plt.barh(categories, values, color='salmon')
plt.title("Horizontal Bar Chart")
plt.xlabel("Value")
plt.show()

🥧 5. Pie Charts — Showing Proportions

Pie charts represent parts of a whole.
Use them sparingly, as comparisons between slices can be imprecise.

import matplotlib.pyplot as plt

labels = ['Apples', 'Bananas', 'Oranges', 'Grapes']
sizes = [30, 25, 20, 25]
colors = ['gold', 'lightgreen', 'coral', 'skyblue']

plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140, shadow=True)
plt.title("Fruit Distribution")
plt.axis('equal')  # Equal aspect ratio makes the pie circular
plt.show()

🔵 6. Scatter Plots — Displaying Relationships

Scatter plots show correlations or distributions between two variables.

import numpy as np

x = np.random.rand(50)
y = x * 2 + np.random.randn(50) * 0.2

plt.scatter(x, y, color='purple', s=60, alpha=0.7, edgecolors='w')
plt.title("Scatter Plot Example")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()

💬 Try adding color (c=) or size (s=) variations to show more dimensions.


📦 7. Histograms — Visualizing Distributions

Histograms reveal how data is distributed across intervals.

data = np.random.randn(1000)

plt.hist(data, bins=30, color='steelblue', edgecolor='black', alpha=0.7)
plt.title("Histogram Example")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()

💡 Adjust bins to change granularity — more bins = more detail.


🧮 8. Multiple Plots and Subplots

Create multiple charts in one figure for comparison.

fig, axes = plt.subplots(1, 2, figsize=(10, 4))

axes[0].plot(years, values, color='royalblue')
axes[0].set_title("Line Chart")

axes[1].bar(categories, values[:4], color='orange')
axes[1].set_title("Bar Chart")

plt.tight_layout()
plt.show()

🧭 9. Adding Annotations and Saving Figures

plt.plot(years, values, marker='o', color='teal')
plt.annotate('Peak', xy=(2021, 180), xytext=(2020.7, 190),
             arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.title("Annotated Line Chart")
plt.show()

# Save the figure
plt.savefig("line_chart.png", dpi=300, bbox_inches='tight')

🧰 10. Common Chart Types and Use Cases

Chart TypeUse CaseFunction
LineTrends over timeplt.plot()
BarCategory comparisonplt.bar()
PieProportions of a wholeplt.pie()
ScatterRelationships between variablesplt.scatter()
HistogramData distributionplt.hist()
SubplotsMultiple charts in one figureplt.subplots()

💡 11. Best Practices


🧭 Conclusion

Matplotlib is the cornerstone of Python visualization — flexible, reliable, and deeply customizable.
By mastering its basic plots, subplots, and styling options, you’ll be ready to move into Seaborn, Plotly, and advanced dashboards.

“Every great visualization starts with clear intent — not code.”