0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Use Matplotlib with NumPy for Data Visualization

You can use numpy to create or manipulate numerical data arrays and then use matplotlib to plot this data visually. Typically, you generate data points with numpy functions like linspace or arange, then pass these arrays to matplotlib.pyplot.plot() to create graphs.
๐Ÿ“

Syntax

To use matplotlib with numpy, first import both libraries. Use numpy to create data arrays, then use matplotlib.pyplot to plot these arrays.

  • import numpy as np: imports numpy with alias np.
  • import matplotlib.pyplot as plt: imports matplotlib plotting functions.
  • x = np.linspace(start, stop, num): creates evenly spaced numbers.
  • plt.plot(x, y): plots y versus x.
  • plt.show(): displays the plot window.
python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)  # 100 points from 0 to 10
y = np.sin(x)  # sine of each x point

plt.plot(x, y)  # plot y vs x
plt.show()  # display the plot
Output
A line graph showing a sine wave from 0 to 10 on the x-axis.
๐Ÿ’ป

Example

This example shows how to create a simple sine wave plot using numpy to generate data and matplotlib to visualize it.

python
import numpy as np
import matplotlib.pyplot as plt

# Create 200 points from 0 to 4*pi
x = np.linspace(0, 4 * np.pi, 200)
# Calculate sine values for each x
y = np.sin(x)

# Plot the sine wave
plt.plot(x, y, label='sin(x)')
plt.title('Sine Wave')
plt.xlabel('x values')
plt.ylabel('sin(x)')
plt.legend()
plt.grid(True)
plt.show()
Output
A labeled line graph showing a smooth sine wave with grid lines.
โš ๏ธ

Common Pitfalls

Common mistakes when using matplotlib with numpy include:

  • Not importing both libraries correctly.
  • Passing mismatched array sizes to plt.plot().
  • Forgetting to call plt.show() to display the plot.
  • Using integer division or wrong data types in numpy arrays.

Always ensure your x and y arrays have the same length and are numeric.

python
import numpy as np
import matplotlib.pyplot as plt

# Wrong: x and y have different lengths
x = np.linspace(0, 10, 50)
y = np.sin(np.linspace(0, 10, 40))  # length mismatch

# This will cause an error
# plt.plot(x, y)

# Correct way
x = np.linspace(0, 10, 50)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Output
A line graph showing sine wave from 0 to 10 on x-axis.
๐Ÿ“Š

Quick Reference

FunctionPurposeExample
np.linspace(start, stop, num)Create evenly spaced numbersnp.linspace(0, 5, 10)
np.sin(array)Calculate sine of each elementnp.sin(x)
plt.plot(x, y)Plot y versus xplt.plot(x, y)
plt.show()Display the plot windowplt.show()
plt.title('text')Add title to plotplt.title('My Plot')
plt.xlabel('text')Label x-axisplt.xlabel('Time')
plt.ylabel('text')Label y-axisplt.ylabel('Value')
plt.grid(True)Show grid linesplt.grid(True)
โœ…

Key Takeaways

Use numpy to create or manipulate numerical data arrays before plotting.
Pass numpy arrays directly to matplotlib plotting functions like plt.plot().
Ensure x and y arrays have the same length to avoid errors.
Always call plt.show() to display your plot window.
Add labels and titles to make your plots clear and informative.