Skip to content

Latest commit

 

History

History
119 lines (86 loc) · 3.52 KB

File metadata and controls

119 lines (86 loc) · 3.52 KB

1. Introduction to Matplotlib and Line Plots

Tip

TL;DR (In 10 Seconds):

  • Matplotlib is Python's foundational data visualization library.
  • import matplotlib.pyplot as plt: Pyplot module provides easy state-based plotting.
  • plt.plot(x, y): Line plot for continuous trends.
  • plt.savefig("chart.png"): Saves chart as image (Always call BEFORE plt.show()).

1. What is Matplotlib and Pyplot?

Data visualization turns raw numbers into intuitive charts. Matplotlib is the core library behind almost all Python data plotting.

For 90% of your plotting needs, use matplotlib.pyplot, imported under the universal alias plt:

import matplotlib.pyplot as plt

2. Basic Line Plot & Customization

Line plots display trends over continuous intervals (like time or temperature):

import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
temp_a = [22, 24, 21, 25, 27]
temp_b = [18, 19, 20, 22, 23]

# 1. Plotting multiple lines on the same chart
plt.plot(days, temp_a, color="red", linestyle="--", marker="o", linewidth=2, label="City A")
plt.plot(days, temp_b, color="blue", linestyle="-", marker="s", linewidth=2, label="City B")

# 2. Titles, Labels, Legend, and Grid
plt.title("Weekly Temperature Trends 🌡️", fontsize=14)
plt.xlabel("Day of Week")
plt.ylabel("Temperature (°C)")
plt.grid(True)
plt.legend()  # Displays legend box using 'label' strings

# 3. Setting Axis Limits & Ticks
plt.ylim(15, 30)  # Restrict Y-axis between 15°C and 30°C

# 4. Save figure before displaying!
plt.savefig("temp_trends.png", dpi=300, bbox_inches="tight")

plt.show()

3. Useful Pyplot Plotting Commands

Command Purpose Example
plt.plot(x, y) Line chart plt.plot(x, y, color="red", marker="o")
plt.title("Header") Main title plt.title("Revenue 2026")
plt.xlabel() / plt.ylabel() Axis labels plt.xlabel("Month")
plt.xlim(min, max) Axis bounds plt.ylim(0, 100)
plt.legend() Display legend box plt.legend(loc="upper left")
plt.grid(True) Toggle grid lines plt.grid(True)
plt.savefig("fn.png") Export high-res image plt.savefig("plot.png", dpi=300)

4. ⚠️ Traps & Mistakes to Avoid

Trap 1: Calling plt.savefig() AFTER plt.show()

# ❌ WRONG: plt.show() clears the canvas buffer after rendering!
# plt.show()
# plt.savefig("chart.png") # 💥 Saves a blank white image!

# ✅ RIGHT: Call plt.savefig() BEFORE plt.show():
plt.savefig("chart.png")
plt.show()

🎯 Self-Check Practice Exercise

Task: Plot a line chart with x = [1, 2, 3, 4] and y = [10, 20, 15, 30]. Set color to "purple", marker to "o", title to "Monthly Sales", and save it as "sales.png".

💡 Click to See Solution
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 15, 30]

plt.plot(x, y, color="purple", marker="o", label="Sales ($k)")
plt.title("Monthly Sales")
plt.xlabel("Quarter")
plt.ylabel("Amount")
plt.grid(True)
plt.legend()

plt.savefig("sales.png", bbox_inches="tight")
plt.show()