Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scatter a 2D numpy array in matplotlib

I have a 4x4 data array like

data = np.array([[0,1,1,1], [1,0,0,1], [1,1,1,0], [0,0,0,1]])

Now I want to scatter this array on a 2D plot.

If data[i,j] is equal to 1, there should be a colored spot at point (x,y)=(i,j). I've tried with scatter plot in matplotlib, but somehow couldn't make it work.

like image 290
dofine Avatar asked May 20 '15 09:05

dofine


People also ask

How do I plot a 2D matrix in matplotlib?

Use matplotlib. pyplot.imshow(X) with X set to a 2d array to plot the array. Use matplotlib. pyplot. show() to display the plot.

Can you plot NumPy array?

In Python, matplotlib is a plotting library. We can use it along with the NumPy library of Python also. NumPy stands for Numerical Python and it is used for working with arrays.


1 Answers

You can do it with

import numpy as np
import matplotlib.pyplot as plt

data = np.array([[0,1,1,1], [1,0,0,1], [1,1,1,0], [0,0,0,1]])

# get the indices where data is 1
x,y = np.argwhere(data == 1).T

plt.scatter(x,y)
plt.show()

However, when you just want to visualize the 4x4 array you can use matshow

plt.matshow(data)
plt.show()
like image 109
plonser Avatar answered Sep 16 '22 14:09

plonser