相当简单:我想知道是否有一种简单的方法可以将色彩图重新缩放到可见区域,在这种情况下由ax.set_xlim.
设置。我要查找的结果图表看起来相同颜色为下面代码中注释掉ax.set_xlim([-2,2])
的颜色。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
X,Y = np.meshgrid(x,y)
Z = X
fig = plt.figure()
ax = fig.add_subplot(111)
cmap = plt.get_cmap('RdYlBu')
cax = ax.contourf(X,Y,Z,256,cmap=cmap, vmin = np.min(Z), vmax=np.max(Z))
cbar = fig.colorbar(cax, cmap=cmap)
ax.set_xlim([-2,2])
plt.show()
答案 0 :(得分:0)
这可能不是最优雅的解决方案,但它会将您的颜色条“重新缩放”到显示范围。注意,如果你没有设置ylim,你需要删除get_ylim。
fig = plt.figure()
ax = fig.add_subplot(111)
cmap = plt.get_cmap('RdYlBu')
# Note - if you don't set ylim as well, ax.get_ylim() returns (0,1) & you'd need to leave that part out
ax.set_xlim(-2,2)
xl = ax.get_xlim()
ax.set_ylim(-1,1)
yl = ax.get_ylim()
XL = np.where(((x>xl[0]))&(x<xl[1]))[0]
YL = np.where(((y>yl[0])&(y<yl[1])))[0].repeat(XL.shape[0]).reshape(-1,XL.shape[0])
XL = XL.repeat(YL.shape[0]).reshape(YL.shape[0],-1)
values = np.linspace(Z[YL,XL].min(),Z[YL,XL].max(),256)
cax = ax.contourf(X,Y,Z,values,cmap=cmap, vmin = values.min(), vmax=values.max())
cbar = fig.colorbar(cax, cmap=cmap)
plt.show()