0
0
NumPydata~5 mins

NumPy with Matplotlib

Choose your learning style9 modes available
Introduction

We use NumPy to create and handle numbers easily. Matplotlib helps us draw pictures from those numbers. Together, they make it simple to see data as graphs.

When you want to draw a line chart of daily temperatures.
When you need to show how sales change over months.
When you want to plot points to see a pattern in data.
When you want to compare two sets of numbers visually.
Syntax
NumPy
import numpy as np
import matplotlib.pyplot as plt

x = np.array([numbers])
y = np.array([numbers])
plt.plot(x, y)
plt.show()

Use np.array to create number lists for plotting.

plt.plot() draws the graph, and plt.show() displays it.

Examples
Simple line graph with 4 points.
NumPy
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4])
y = np.array([10, 20, 25, 30])
plt.plot(x, y)
plt.show()
Plotting a smooth sine wave using many points.
NumPy
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 values for each x

plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x values')
plt.ylabel('sin(x)')
plt.show()
Two lines on the same graph with labels.
NumPy
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4])
y1 = np.array([10, 20, 25, 30])
y2 = np.array([15, 18, 22, 28])

plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.legend()
plt.show()
Sample Program

This program draws sine and cosine waves on the same graph to compare them.

NumPy
import numpy as np
import matplotlib.pyplot as plt

# Create 50 points from 0 to 4*pi
x = np.linspace(0, 4 * np.pi, 50)

# Calculate sine and cosine values
sin_y = np.sin(x)
cos_y = np.cos(x)

# Plot sine and cosine
plt.plot(x, sin_y, label='Sine')
plt.plot(x, cos_y, label='Cosine')

# Add title and labels
plt.title('Sine and Cosine Waves')
plt.xlabel('x values')
plt.ylabel('y values')

# Show legend
plt.legend()

# Display the plot
plt.show()
OutputSuccess
Important Notes

Always import NumPy as np and Matplotlib pyplot as plt by convention.

Use np.linspace(start, stop, num_points) to create smooth ranges of numbers.

Adding labels and titles helps understand the graph better.

Summary

NumPy helps create and manage numbers easily.

Matplotlib draws graphs from those numbers.

Together, they make data easy to see and understand.