UnlimitedQuestions
UnlimitedQuestions

Reputation: 33

How to make 2D colored grid with 3 arrays

I have three arrays of equal length x, y, and z. The x and y arrays are the x-axis and y-axis for the grid. The z array will determine the color of the the grid block. For example,

x = [10, 10, 10, 20, 20, 20, 30, 30, 30]
y = [10, 20, 30, 10, 20, 30, 10, 20, 30]
z = [99, 54, 32, 67, 71, 88, 100, 15, 29]

It is easy to make 3D plots out of this like

ax.plot_trisurf(x, y, z, cmap=cm.RdYlGn)

or

ax.bar3d(x, y, [0] * len(x), 100, 100, z, cmap=cm.RdYlGn)

But I am looking for something like this grid

Another problem is that the way my z array is generated, it isn't in order by index. So my x, y, and z arrays could look like this.

x = [30, 10, 20, 20, 30, 10, 10, 30, 20]
y = [10, 20, 30, 10, 30, 30, 10, 20, 20]
z = [100, 54, 88, 67, 29, 32, 99, 15, 71]

Upvotes: 1

Views: 471

Answers (1)

pingul
pingul

Reputation: 3473

Here is a small example for your specific problem. I'm converting your x and y indices to positions in an array looking at your data -- you might need to change this yourself.

import numpy as np
import matplotlib.pyplot as plt

x = [10, 10, 10, 20, 20, 20, 30, 30, 30]
y = [10, 20, 30, 10, 20, 30, 10, 20, 30]
z = [99, 54, 32, 67, 71, 88, 100, 15, 29]

# Convert x/y to indices. This only works if you have a rigid grid (which seems to be the case, but you might have to change the transform for your case)
x = (np.array(x)/10 - 1).astype(int)
y = (np.array(y)/10 - 1).astype(int)

# Create the image. Default color is black
z_im = np.zeros((x.max() + 1, y.max() + 1, 3))

# Go through z and color acoordingly -- only gray right now
for i, v in enumerate(z):
    z_im[x[i], y[i]] = (v, v, v)

fig, ax = plt.subplots()
ax.imshow(z_im)
plt.show()

enter image description here

Upvotes: 1

Related Questions