简体   繁体   中英

how to plot a x-y grid of e.g. squares with colours read from an array

I have separate arrays of x and y coordinates, and a z-array of corresponding values. I wish to make a plot that has squares at each x and y coordinate that have colours set from the z array - something similar to this . I have searched quite hard on google to find how I can do this, but to no avail. The matplotlib.pyplot.scatter function needs the color array scaled from 0-1, so I can't see how that could be used in this circumstance. Any help is much appreciated.

Thanks Andrew. I see how that works now. The thing is my z-array is just one column of numbers. Since they are not in any sensible order, it would be difficult to just re-shape the array into 2D to use pcolor.

I have come up with a much better solution using a for loop to append rectangle patches to a patch collection, then assign a colour map to the whole collection and plot.

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
import matplotlib.patches as mpatches

fig = plt.figure(figsize=(9,5))
ax = plt.axes([0.1,0.1,0.7,0.7])
cmap = matplotlib.cm.jet
patches = []

data=np.array([4.5,8.6,2.4,9.6,11.3])
data_id_nos=np.array([5,6,9,8,7])
x_coords=np.array([3.12,2.6,2.08,1.56,1.04])
y_coords=np.array([6.76,6.24,5.72,5.20,4.68])
coord_id_nos=np.array([7,9,6,5,8])    

for i in range(len(data_id_nos)):
        coords=(x_coords[np.where(coord_id_nos == data_id_nos[i])],y_coords[np.where(coord_id_nos == data_id_nos[i])])
        art = mpatches.Rectangle(coords,0.50,0.50,ec="none")
        patches.append(art)

#create collection of patches for IFU position
IFU1 = PatchCollection(patches, cmap=cmap)
#set the colours = data values
IFU1.set_array(np.array(data))
ax.add_collection(IFU1)
plt.axis('scaled')
plt.xlabel('x (arcsecs)')
plt.ylabel('y (arcsecs)')

我猜你想pcolor ,如图所示这里

You need to do something like this

x = np.arange(10)
y = np.arange(10)
z = np.zeros([10,10])
z[1,5] = 10
z[2,7] = 20
z[3,9] = 30
pcolor(x,y,z)

with this precise code the last point will be off the axis, but it should give you the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM