Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot an array in Python using Matplotlib?
To plot an array in Python, we use Matplotlib, a powerful plotting library. This tutorial shows how to create line plots from NumPy arrays with proper formatting and styling.
Basic Array Plotting
Here's how to plot a simple array using Matplotlib ?
import numpy as np
import matplotlib.pyplot as plt
# Create arrays
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 1, 5, 3])
# Create the plot
plt.figure(figsize=(8, 5))
plt.plot(x, y, color="red", marker='o')
plt.title("Basic Array Plot")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.grid(True, alpha=0.3)
plt.show()
Single Array Plotting
When plotting a single array, Matplotlib uses array indices as x-coordinates ?
import numpy as np
import matplotlib.pyplot as plt
# Single array - indices used as x-coordinates
data = np.array([5, 4, 1, 4, 5])
plt.figure(figsize=(8, 5))
plt.plot(data, color="blue", marker='s', linewidth=2)
plt.title("Single Array Plot")
plt.xlabel("Index")
plt.ylabel("Value")
plt.grid(True, alpha=0.3)
plt.show()
Multiple Plotting Styles
You can customize plots with different line styles, markers, and colors ?
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5])
y1 = np.array([1, 4, 2, 5, 3])
y2 = np.array([2, 1, 4, 3, 5])
plt.figure(figsize=(10, 6))
# Different styles for multiple arrays
plt.plot(x, y1, 'r-o', label='Array 1', linewidth=2)
plt.plot(x, y2, 'g--s', label='Array 2', linewidth=2)
plt.title("Multiple Array Plots")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Key Plotting Parameters
| Parameter | Purpose | Example Values |
|---|---|---|
color |
Line color | 'red', 'blue', '#FF5733' |
marker |
Point markers | 'o', 's', '^', '*' |
linewidth |
Line thickness | 1, 2, 3 |
linestyle |
Line pattern | '-', '--', '-.', ':' |
Advanced Example with Subplots
For comparing multiple arrays side by side ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
data1 = np.array([1, 3, 2, 4, 5])
data2 = np.array([2, 1, 4, 3, 5])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# First subplot
ax1.plot(data1, 'ro-', linewidth=2)
ax1.set_title('Array 1')
ax1.set_xlabel('Index')
ax1.set_ylabel('Value')
ax1.grid(True, alpha=0.3)
# Second subplot
ax2.plot(data2, 'bs-', linewidth=2)
ax2.set_title('Array 2')
ax2.set_xlabel('Index')
ax2.set_ylabel('Value')
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Conclusion
Matplotlib makes it easy to plot NumPy arrays using plt.plot(). Use single arrays for index-based plotting or provide both x and y arrays for custom coordinates. Customize with colors, markers, and labels for professional-looking visualizations.
Advertisements
