NumPy with Matplotlib basics
NumPy makes the numbers and Matplotlib draws them, and the two are almost always used together.
In this page:
Syntax
import matplotlib.pyplot as plt
x = np.linspace(start, stop, num)
y = np.function(x)
plt.plot(x, y)
plt.show()
NumPy with Matplotlib basics
Matplotlib plots NumPy arrays directly. Use linspace for the x values and a ufunc like np.sin for the y values, then call plt.plot. Below, the chart is drawn off-screen and saved to memory so you can see it worked.
Note:
In a normal script or notebook, call plt.show() to display the plot window.
Example: NumPy with Matplotlib basics
import io
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine wave")
buf = io.BytesIO()
plt.savefig(buf, format="png")
print("points plotted:", len(x))
print("png rendered:", buf.getbuffer().nbytes > 0)
# Output:
# points plotted: 100
# png rendered: True
Related Topics
Common Mistakes
- Forgetting plt.show in scripts
- Passing arrays of different lengths
- Using too few points for a smooth curve
Chapter Summary
- Matplotlib accepts NumPy arrays
- linspace builds x values
- ufuncs build y values
- plt.show displays the figure
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: