Matplotlib Plotting
Compose line charts, customize aesthetics, and highlight key data points using Matplotlib's plotting primitives.
Basic Line Plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 200)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, color="royalblue", linewidth=2)
ax.set_title("Sine Wave")
ax.set_xlabel("x")
ax.set_ylabel("sin(x)")
plt.show()Multiple Series
Plot multiple datasets on the same axes. Use labels and legends to distinguish series.
x = np.linspace(0, 10, 200)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)", linestyle="--")
ax.legend()
plt.show()Highlighting Key Points
Combine plot() with markers to call attention to thresholds or peaks.
peak_x = np.pi / 2
peak_y = 1
fig, ax = plt.subplots()
ax.plot(x, np.sin(x))
ax.plot(peak_x, peak_y, marker="o", color="crimson", markersize=8)
ax.annotate("Peak", (peak_x, peak_y), xytext=(peak_x + 0.5, peak_y),
arrowprops=dict(arrowstyle="->"))Customizing Lines
Control color, line width, style, and transparency with keyword arguments:
colororc: color names, hex codes, or RGB tuples.linewidth(lw): thickness in points.linestyle(ls):-,--,-.,:.alpha: opacity (0 to 1).
Grid and Limits
Improve readability by adding grid lines and constraining axes limits.
ax.grid(True, linestyle=":", alpha=0.6)
ax.set_xlim(0, 10)
ax.set_ylim(-1.1, 1.1)Saving Styled Plots
Persist stylized plots for reports. Provide consistent fonts and colors aligned with brand guidelines circulated via info.studygrid@gmail.com.
fig.savefig("sine-wave-branded.svg", facecolor="white", dpi=200)Next Steps
Learn how to control markers in detail to highlight data points across charts.
Multiple Lines and a Legend
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
plt.plot(x, [1, 4, 9, 16], label="squares")
plt.plot(x, [1, 8, 27, 64], label="cubes")
plt.legend() # shows the labels
plt.show()Call plt.plot several times before show() to layer multiple series on one chart, then add a legend().
Try It Yourself
Exercise: Plot both y = x and y = x² on the same axes with a legend.
Show solution
import matplotlib.pyplot as plt
x = list(range(6))
plt.plot(x, x, label="linear")
plt.plot(x, [v**2 for v in x], label="quadratic")
plt.legend()
plt.show()Key Takeaways
- Plot multiple series by calling
plotrepeatedly. - Pass
label=and calllegend()to identify each line.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Plotting (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Plotting that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 4, 0.1)
plt.plot(x, x**2, "g--")
plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Plotting as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.