Set limits on matplotlib color panel without changing the actual schedule

I would like to create a pseudocolor plot (e.g. contour or contourf ) and a color panel. For practical reasons, I want the color bar range to be different from the one shown below.

In the example below, the Z data has a range from 0 to 10000, which is displayed in the color palette. The color range is the same.

 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]) pyplot.show() 

plot

Now I would like to β€œzoom in” on the color bar, i.e. create a color panel with a range from 3000 to 6000. This new colorbar will still serve as a legend and give the right colors for each tick (3000 = blue, 6000 = yellow). Neither cbar.set_clim() nor cf.set_clim() do this.

+4
source share
1 answer

In general, suppressing sections of your color bar is a bad idea, but here's a very 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 it hacks because it affects a whole bunch of internal elements of the color panel. cbar.outline is a Line2D object that is a black box around the color bar, set_ydata sets ydata at the corners to match the subregion you want to look at. Try with this line and see what happens.

You might want to learn the colormap clip function.

+3
source

Source: https://habr.com/ru/post/1482192/


All Articles