Set limits on a matplotlib colorbar without changing the actual plot

我只是一个虾纸丫 提交于 2019-12-05 12:39:19

In general suppressing sections of your color bar is a Bad Idea, but here is a super hacky way to do it.

import numpy
from matplotlib import pyplot

X = numpy.arange(100)
Y = numpy.arange(100)
Z = numpy.arange(100**2).reshape((100,100))

f = pyplot.figure()
ax = f.gca()
cf = ax.contourf(X,Y,Z,100)
cbar = f.colorbar(cf, ticks=[3000,4000,5000,6000])
cbar.ax.set_ylim([cbar.norm(3000), cbar.norm(6000)])
cbar.outline.set_ydata([cbar.norm(3000)] * 2 + [cbar.norm(6000)] * 4 + [cbar.norm(3000)] * 3)
cbar.ax.set_aspect(60)  # <- tweak this to get the aspect ratio you want
pyplot.show()

I call this hacky because it touches a whole bunch of the internals of the colorbar. cbar.outline is a Line2D object that is the black box around the colorbar, the set_ydata sets the ydata on the corners to match the sub-region you want to look at. Try it with out that line and see what happens.

You might want to look into colormap's clip feature.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!