1

I am trying to make some contourf figures with the option 'extend=both'. However, the colors outside the color range (both max and min) does not show in the figure. When calling the colorbar function after contourf, the outside colors appears, but I want to make figures without colorbars.

Here is the sample code.

import numpy as np
import matplotlib.pyplot as plt

x=np.arange(10)
y=np.arange(10)

z=np.zeros((10,10))
for n in range(10):
    for m in range(10):
        z[n,m]=x[n]*y[m]

N=255.
rgb=[(187/N,220/N,200/N),
(120/N,185/N,171/N), 
( 52/N,150/N,142/N), 
( 26/N,105/N, 95/N)] 

interval=[1,5,10,20,50]

cf=plt.contourf(x,y,z,colors=rgb,levels=interval,extend='both')
cf.cmap.set_under((255/N, 255/N,229/N))
cf.cmap.set_over((0/N, 60/N,48/N))
#plt.colorbar()

plt.savefig('test1')
plt.close()

cf=plt.contourf(x,y,z,colors=rgb,levels=interval,extend='both')
cf.cmap.set_under((255/N, 255/N,229/N))
cf.cmap.set_over((0/N, 60/N,48/N))
plt.colorbar()

plt.savefig('test2')
plt.close()

enter image description here

enter image description here

test1.png does not show the outside color (<1 and >50). I want to get the figure like test2.png, but without colorbar.

Does anyone know how to solve this problem?

My environment is, Python=3.6.9 Matplotlib=2.1.1

Thank you.

Mr. T
  • 11,960
  • 10
  • 32
  • 54
  • 1
    You have to provide your colormap to contour. [Number four in this matplotlib example shows you how.](https://matplotlib.org/2.0.0/examples/pylab_examples/contourf_demo.html) – Mr. T Feb 07 '21 at 11:44
  • And when I say "number four", I obviously mean number three producing the four subplots. Something, something, higher mathematics, something. – Mr. T Feb 07 '21 at 11:54
  • If you modify the `interval=[0,1,5,10,20,50,80,100]` interval value to this, I think you can see why. If the color bar is not specified, it will be divided by the interval value. If a color bar is specified, the lowest value is 0, so the colors will be different. I don't know enough about this to explain it correctly. Just a guess I got by changing the interval value. – r-beginners Feb 07 '21 at 13:15
  • A trick could be to create the colorbar and immediately remove it. `plt.colorbar().remove()`. You'll need to create a dummy `ax` for the colorbar to avoid that the colorbar reduces the size of the main plot (as in the second example in [this tutorial](https://matplotlib.org/3.3.4/gallery/axes_grid1/demo_colorbar_with_inset_locator.html)). – JohanC Feb 07 '21 at 19:16

0 Answers0