Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

python - How to do colored 2D 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 = [100, 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

np.meshgrid returns a tuple of two 2D arrays, which you can unpack directly

X,Y = np.meshgrid(x,y)

However, you don't need to those for an imshow plot. What you need and what you lack in your code is the 2D array of z values. This would be the array to provide to imshow.

img = plt.imshow(Z)

If you want to use meshgrid instead, you can use your X and Y values,

plt.pcolormesh(X,Y,Z)

Seeing the example data, you can use imshow:

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

import matplotlib.pyplot as plt
import numpy as np

z = np.array(z).reshape(3,3)

plt.imshow(z,extent=[5,35,5,35])

plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...