简体   繁体   中英

Matplotlib contour plot using specific data points from a set

I am very sorry for the cumbersome title, but I don't find a way to express it clearly. The task that I should accomplish here is, given three numpy arrays containing coordinate matrices (X, Y) and the evaluation of a real function in this grid (Z); to obtain contour plots of the data. However, some of the coordinates give place to unacceptable Z values, and shouldn't be considered in the plots. What I have done so far:

cmap = plt.cm.get_cmap("winter")
cmap.set_under("magenta")
cmap.set_over("yellow")

with PdfPages('myplot.pdf') as pdf:
     fig = plt.figure()
     CS = plt.contourf(X, Y, Z, cmap=cmap)
     cbar = plt.colorbar(CS)
     cbar.ax.set_ylabel('Z')
     plt.xlabel('X (\AA)')
     plt.ylabel('Y (\AA)')
     plt.tight_layout()
     pdf.savefig(fig)

However, I don't find a proper way to restrict the values that should be taken into account in the plots (something like Zmin < Z < Zmax ). I thought on the methods set_under and set_over of cmap , but it doesn't seem to be the way. Any suggestion abut this problem? Thank you very much in advance.

There are several ways to achieve the desired effect:

1) cap your Z-values directly as below, then plot the resulting array:

Z2 = Z.copy()
Z2[Z<Zmin] = Zmin
Z2[Z>Zmax] = Zmax
CS = plt.contourf(X, Y, Z2, cmap=cmap)

2) rescale your colorbar using the vmin and vmax arguments:

CS = plt.contourf(X, Y, Z, cmap=cmap, vmin=Zmin, vmax=Zmax)

Edit:

Misread your question / intent. If you want to mark the out-of-range values, then either set them to NaNs (in which case the corresponding locations will be white), or use your set_under / set_over approach together with the vmin and vmax arguments.

1) set out-of-range values to NaN:

Z2 = Z.copy()
Z2[Z<Zmin] = np.nan
Z2[Z>Zmax] = np.nan
CS = plt.contourf(X, Y, Z2, cmap=cmap)

2) set_under and set_over , then set limits using the vmin and vmax arguments:

cmap.set_under("magenta")
cmap.set_over("yellow")
CS = plt.contourf(X, Y, Z, cmap=cmap, vmin=Zmin, vmax=Zmax)

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