wnukers
wnukers

Reputation: 69

Creating 2d histogram from 2d numpy array

I have a numpy array like this:

[[[0,0,0], [1,0,0], ..., [1919,0,0]],
[[0,1,0], [1,1,0], ..., [1919,1,0]],
...,
[[0,1019,0], [1,1019,0], ..., [1919,1019,0]]]

To create I use function (thanks to @Divakar and @unutbu for helping in other question):

def indices_zero_grid(m,n):
     I,J = np.ogrid[:m,:n]
     out = np.zeros((m,n,3), dtype=int)
     out[...,0] = I
     out[...,1] = J
     return out

I can access this array by command:

>>> out = indices_zero_grid(3,2)
>>> out
array([[[0, 0, 0],
        [0, 1, 0]],

       [[1, 0, 0],
        [1, 1, 0]],

       [[2, 0, 0],
        [2, 1, 0]]])
>>> out[1,1]
array([1, 1,  0])

Now I wanted to plot 2d histogram where (x,y) (out[(x,y]) is the coordinates and the third value is number of occurrences. I've tried using normal matplotlib plot, but I have so many values for each coordinates (I need 1920x1080) that program needs too much memory.

Upvotes: 0

Views: 1126

Answers (1)

unutbu
unutbu

Reputation: 879371

If I understand correctly, you want an image of size 1920x1080 which colors the pixel at coordinate (x, y) according to the value of out[x, y].

In that case, you could use

import numpy as np
import matplotlib.pyplot as plt

def indices_zero_grid(m,n):
     I,J = np.ogrid[:m,:n]
     out = np.zeros((m,n,3), dtype=int)
     out[...,0] = I
     out[...,1] = J
     return out

h, w = 1920, 1080
out = indices_zero_grid(h, w)
out[..., 2] = np.random.randint(256, size=(h, w))
plt.imshow(out[..., 2])
plt.show()

which yields

enter image description here

Notice that the other two "columns", out[..., 0] and out[..., 1] are not used. This suggests that indices_zero_grid is not really needed here.

plt.imshow can accept an array of shape (1920, 1080). This array has a scalar value at each location in the array. The structure of the array tells imshow where to color each cell. Unlike a scatter plot, you don't need to generate the coordinates yourself.

Upvotes: 1

Related Questions