Tyler
Tyler

Reputation: 4709

convert matrix to image

How would I go about going converting a list of lists of ints into a matrix plot in Python?

The example data set is:

[[3, 5, 3, 5, 2, 3, 2, 4, 3, 0, 5, 0, 3, 2],
 [5, 2, 2, 0, 0, 3, 2, 1, 0, 5, 3, 5, 0, 0],
 [2, 5, 3, 1, 1, 3, 3, 0, 0, 5, 4, 4, 3, 3],
 [4, 1, 4, 2, 1, 4, 5, 1, 2, 2, 0, 1, 2, 3],
 [5, 1, 1, 1, 5, 2, 5, 0, 4, 0, 2, 4, 4, 5],
 [5, 1, 0, 4, 5, 5, 4, 1, 3, 3, 1, 1, 0, 1],
 [3, 2, 2, 4, 3, 1, 5, 5, 0, 4, 3, 2, 4, 1],
 [4, 0, 1, 3, 2, 1, 2, 1, 0, 1, 5, 4, 2, 0],
 [2, 0, 4, 0, 4, 5, 1, 2, 1, 0, 3, 4, 3, 1],
 [2, 3, 4, 5, 4, 5, 0, 3, 3, 0, 2, 4, 4, 5],
 [5, 2, 4, 3, 3, 0, 5, 4, 0, 3, 4, 3, 2, 1],
 [3, 0, 4, 4, 4, 1, 4, 1, 3, 5, 1, 2, 1, 1],
 [3, 4, 2, 5, 2, 5, 1, 3, 5, 1, 4, 3, 4, 1],
 [0, 1, 1, 2, 3, 1, 2, 0, 1, 2, 4, 4, 2, 1]]

To give you an idea of what I'm looking for, the function MatrixPlot in Mathematica gives me this image for this data set:

enter image description here

Thanks!

Upvotes: 21

Views: 25593

Answers (3)

Alexander Martins
Alexander Martins

Reputation: 383

You can also use pyplot from matplotlib, follows the code:

from matplotlib import pyplot as plt


plt.imshow(
[[3, 5, 3, 5, 2, 3, 2, 4, 3, 0, 5, 0, 3, 2],
 [5, 2, 2, 0, 0, 3, 2, 1, 0, 5, 3, 5, 0, 0],
 [2, 5, 3, 1, 1, 3, 3, 0, 0, 5, 4, 4, 3, 3],
 [4, 1, 4, 2, 1, 4, 5, 1, 2, 2, 0, 1, 2, 3],
 [5, 1, 1, 1, 5, 2, 5, 0, 4, 0, 2, 4, 4, 5],
 [5, 1, 0, 4, 5, 5, 4, 1, 3, 3, 1, 1, 0, 1],
 [3, 2, 2, 4, 3, 1, 5, 5, 0, 4, 3, 2, 4, 1],
 [4, 0, 1, 3, 2, 1, 2, 1, 0, 1, 5, 4, 2, 0],
 [2, 0, 4, 0, 4, 5, 1, 2, 1, 0, 3, 4, 3, 1],
 [2, 3, 4, 5, 4, 5, 0, 3, 3, 0, 2, 4, 4, 5],
 [5, 2, 4, 3, 3, 0, 5, 4, 0, 3, 4, 3, 2, 1],
 [3, 0, 4, 4, 4, 1, 4, 1, 3, 5, 1, 2, 1, 1],
 [3, 4, 2, 5, 2, 5, 1, 3, 5, 1, 4, 3, 4, 1],
 [0, 1, 1, 2, 3, 1, 2, 0, 1, 2, 4, 4, 2, 1]], interpolation='nearest')

plt.show()

The output would be:

Plot of the matrix

Upvotes: 0

Dr. belisarius
Dr. belisarius

Reputation: 61056

You may try

from pylab import *
A = rand(5,5)
figure(1)
imshow(A, interpolation='nearest')
grid(True)

enter image description here

source

Upvotes: 18

user180100
user180100

Reputation:

Perhaps matshow() from matplotlib is what you need.

Upvotes: 9

Related Questions