I want to import a numpy
matrix in a matplotlib
plot. Let’s say that I have this matrix:
JavaScript
x
4
1
[[ 1, 2, 3, 4],
2
[ 5, 6, 7, 8],
3
[ 9,10,11,12]]
4
In a scale from 0 to 3 of the x axis, I want to plot the points
JavaScript
1
5
1
(0,1), (0,5), (0,9),
2
(1,2), (1,6), (1,10),
3
(2,3), (2,7), (2,11),
4
(3,4), (3,8), (3,12)
5
This is the code I use:
JavaScript
1
11
11
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
matrix = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
5
plt.grid(True)
6
for i in range(matrix.shape[0]):
7
for j in range(matrix.shape[1]):
8
plt.plot(j,matrix[i][j],'ro')
9
10
plt.show()
11
and this is the outcome:
Yet, if I have to use a large array of let’s say (1000×1000) elements or more, this procedure is going to be extremely slow. I wander if there is a method in matplotlib
in which the array is inserted in the plot without the need to “manually” insert each one element.
Also (and I know that this should be a different question) if the above question solved, is there an easy way to clear the drawing in order to update with a new matrix?
Advertisement
Answer
JavaScript
1
8
1
a = np.array([
2
[ 1, 2, 3, 4],
3
[ 5, 6, 7, 8],
4
[ 9,10,11,12]])
5
b = np.tile(np.arange(a.shape[1]), (a.shape[0], 1))
6
7
plt.scatter(b, a)
8