← Back to NumPy Course | Chapter 12: Advanced Topics | Lesson 7 of 7

NumPy with Matplotlib basics

NumPy makes the numbers and Matplotlib draws them, and the two are almost always used together.
Syntax
python
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

python
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
  1. Forgetting plt.show in scripts
  2. Passing arrays of different lengths
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.