Python/Matplotlib: colobar with spacing='proportional' not work well

Viewed 310

I want to create a colorbar with proportional spacing, but when I use spacing='proportional', the colorbar does not work well and it gives me this error:

anaconda3/envs/env_py01/lib/python3.6/site-packages/matplotlib/colorbar.py:1094: RuntimeWarning: invalid value encountered in double_scalars
  automin = (y[2] - y[1]) / clen
anaconda3/envs/env_py01/lib/python3.6/site-packages/matplotlib/colorbar.py:1095: RuntimeWarning: invalid value encountered in double_scalars
  automax = (y[-2] - y[-3]) / clen

When I use spacing='uniform' there are not error, however the colorbar has not a proportional spacing. I also tried using boundaries but I did not get good results. This is my code:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib.colors import BoundaryNorm

x = np.arange(-6,6,0.25)
y = np.arange(-6,6,0.25)
x, y = np.meshgrid(x,y)
z = np.random.random(x.shape)*10.0


newcolors = np.vstack((plt.cm.YlGn(np.linspace(0, 1, 4))[1:,:], plt.cm.Blues(np.linspace(0, 1, 6))))
palette = ListedColormap(newcolors, name='test')

palette.set_over('darkred')
palette.set_under('yellow')

tickslabels=[0.5,1.0,1.5,2.0,4.0,6.0,8.0,10.0,12.0,14.0]
norm=BoundaryNorm(tickslabels, palette.N)


fig1 = plt.figure('spacing = uniform')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both', norm=norm)
cbar=plt.colorbar(img, ticks=tickslabels, spacing='uniform')
plt.title('spacing = uniform')


fig2 = plt.figure('spacing = proportional')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both', norm=norm)
cbar=plt.colorbar(img, ticks=tickslabels, spacing='proportional')
plt.title('spacing = proportional')


fig3 = plt.figure('spacing = proportional and boundaries')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both', norm=norm)
cbar=plt.colorbar(img, ticks=tickslabels, spacing='proportional', boundaries=[-100.0]+tickslabels+[100.0])
plt.title('spacing = proportional and boundaries')

plt.show()

spacing='uniform' spacing='proportional' spacing='proportional' and boundaries

What I did wrong?

0 Answers
Related