SwadhyAI Notes

All Python notes

Matplotlib Pyplot 📉

The State Machine

pyplot is a collection of functions that make Matplotlib work like MATLAB. It maintains the "state" of the plot, meaning it remembers the current figure and plotting area you are working on.

🎮 Analogy: The Remote Control

Think of pyplot as a TV Remote.
- You don't tell the TV "Draw a pixel at x,y".
- You press "Channel Up" (plot), "Volume Up" (title), or "Mute" (grid).
- The remote remembers which TV it's pointing at (Current Figure).

✨ Plotting Points

The plot() function is the workhorse of Pyplot. It draws lines and/or markers.

python
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 8])
y = np.array([3, 10])

plt.plot(x, y)
plt.show()

🎯 Real-World Application: Lab Experiments

Scientists use Pyplot to quickly visualize data from sensors or experiments to check for correlations.

🔄 Managing State

Since Pyplot remembers the current figure, subsequent calls modify the same plot unless you create a new one.

python
plt.plot(x, y)
plt.title("My Plot") # Adds title to the CURRENT plot
plt.xlabel("X Axis") # Adds label to the CURRENT plot

💡 Clearing the Plot

If you want to start fresh without closing the window, you can use:

  • plt.clf() - Clear the current Figure.
  • plt.cla() - Clear the current Axes.