Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set colorbar range with contourf

This would appear to be a duplicate of this question:

Set Colorbar Range in matplotlib

Essentially I want to set the colorbar range to set limits, e.g. 0 to 2. When I use vmin and vmax, the range of colors in contourf is correctly set, but colorbar only shows the clipped range, i.e. the solution in the link doesn't seem to work when using contourf. Am I missing something obvious?

import numpy as np
import matplotlib.pyplot as plt
fld=np.random.rand(10,10)
img=plt.contourf(fld,20,cmap='coolwarm',vmin=0,vmax=2)
plt.colorbar(img)

Resulting in

enter image description here

How can I force the colorbar range to be 0 to 2 with contourf?

like image 960
Adrian Tompkins Avatar asked Dec 05 '18 22:12

Adrian Tompkins


People also ask

What is the difference between contour and Contourf?

contour() and contourf() draw contour lines and filled contours, respectively. Except as noted, function signatures and return values are the same for both versions. contourf() differs from the MATLAB version in that it does not draw the polygon edges. To draw edges, add line contours with calls to contour() .

How do I use Contourf in Matplotlib?

The contourf() function in pyplot module of matplotlib library is used to plot contours. But contourf draw filled contours, while contourf draws contour lines. Parameters: This method accept the following parameters that are described below: X, Y: These parameter are the coordinates of the values in Z.

How do you add a Colorbar to a contour plot in Python?

A color bar can be added to the filled contour plot using either the pyplot. colorbar() function or the figure. colorbar() method.


1 Answers

contourf indeed works a bit differently than other ScalarMappables. If you specify the number of levels (20 in this case) it will take them between the minimum and maximum data (approximately). If you want to have n levels between two specific values vmin and vmax you would need to supply those to the contouring function

levels = np.linspace(vmin, vmax, n+1)
plt.contourf(fld,levels=levels,cmap='coolwarm')

Complete code:

import numpy as np
import matplotlib.pyplot as plt
fld=np.random.rand(10,10)
levels = np.linspace(0,2,21)
img=plt.contourf(fld,levels=levels,cmap='coolwarm')
plt.colorbar(img)
plt.show()

enter image description here

like image 102
ImportanceOfBeingErnest Avatar answered Sep 28 '22 03:09

ImportanceOfBeingErnest