Same color bar range for different plots - Matplotlib

有些话、适合烂在心里 提交于 2019-12-06 02:52:51

If you want the colors in the colorbars to correspond to the same values within two contour plots, then you need to not only control the colorbar, but also control the levels in the contour plot. That is, to compare the same levels between the plots, the plots should have the same contour levels. This is easy to do. Here's an example of that plot:

There are two ways: 1) calculate the levels ahead of time; 2) use the levels from one plot to set the levels in the other. I'll do the second, since from this it should be clear how to do the first (using, for example, levels = numpy.linspace(v_min, vmax, 10), though, to be clear, I'm not using this here, but am letting mpl calculate the levels).

First, here I'm also using:

Za = 10.0 * (Z2 - Z1)
Zb = 6.0 * (Z2 - Z1)   # 6, rather than 5

Then, to plot:

def plot_contour(x_dim, y_dim, x_steps, y_steps, scalar_field, file_path, v_min, v_max, levels=None):
    x, y = numpy.mgrid[-x_dim/2:x_dim/2:x_steps*1j, -y_dim/2:y_dim/2:y_steps*1j]
    cs = plt.contourf(x, y, scalar_field, zorder=1, cmap=cm.jet, extent=[-x_dim/2.0, x_dim/2.0, -y_dim/2.0, y_dim/2.0], vmin=v_min, vmax=v_max, levels=levels)
    plt.colorbar(cs)
    return cs.levels

v_min, v_max = bounds([Za, Zb])

plt.figure()
plt.subplot(121)
levels = plot_contour(x_dim, y_dim, x_steps, y_steps, Za, 'Za', v_min, v_max)
plt.subplot(122)
plot_contour(x_dim, y_dim, x_steps, y_steps, Zb, 'Zb', v_min, v_max, levels=levels) 
plt.show()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!