首页 > 解决方案 > 为 python matplotlib.pyplot 等高线图指定 x 和 y 范围

问题描述

我想制作一个不包括一些坐标的等高线图,例如每个大于某个阈值的 x 坐标,比如说 9。我不是在问如何设置轴范围,因为稍后我们会在其中过度绘制其他东西x>9 的区域。

制作等高线图很简单:

import matplotlib.pyplot as plt
import numpy as np

# create x and y array
Nx = 20
Ny = 30
x = np.linspace(0,10,Nx)
y = np.linspace(0,10,Ny)

# data to plot
z = np.random.rand( Ny, Nx )

# create grid for contours
xx, yy = np.meshgrid(x, y)

fig = plt.figure( figsize=(8,6) )
ax1 = fig.add_subplot( 1,1,1 )
ax1.contourf( xx, yy, z )

plt.show()

我天真的想法是使用类似的东西

ax1.contourf( xx[np.where(xx<9)], yy[np.where(xx<9)], z[np.where(xx<9)] )

但这不起作用,因为索引是如何从np.where. 我的下一个方法如下:

ax1.contourf( xx[ np.where(xx<9)[0],np.where(xx<9)[1] ], 
              yy[ np.where(xx<9)[0],np.where(xx<9)[1] ], 
              z[  np.where(xx<9)[0],np.where(xx<9)[1] ] 
            )

这也行不通。两种情况下的错误消息都是

TypeError: Input z must be a 2D array.

显然我做错了索引。任何提示或建议如何以正确的方式做到这一点将不胜感激。

标签: pythonnumpymatplotlib

解决方案


您可以通过简单地设置 to 的相应值来做到这z一点np.nan。添加例如

cut1 = xx > 6
cut2 = yy > 2.6
cut3 = yy <= 4.1

z[cut1 & cut2 & cut3] = np.nan

之前ax1.contourf(xx, yy, z)会导致

在此处输入图像描述


推荐阅读