Reputation: 145
I create a custom cmap and ticklabels to make a plot with contourf, but not all the ticklabels nor all the colors are considered by the colorbar, however when I use imshow, I get the result that I want. 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.sqrt(x**2+y**2)
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, len(tickslabels)-1)
fig1 = plt.figure('imshow')
img=plt.imshow(z, cmap=palette, norm=norm)
plt.colorbar(img, ticks=tickslabels, spacing='proportional', extend='both')
plt.title('imshow')
fig2 = plt.figure('contourf')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both') #norm=norm)
plt.colorbar(img, ticks=tickslabels, spacing='proportional', extend='both')
plt.title('contourf')
plt.show()
This are the results using imshow and contourf. Pay attention on colorbar of imshow, the green colors go from 0.5 until 2.0 and the blue colors go from 2.0 until 14.0, this is the result that I want. However using contourf the result is not the same. What is my error? I forget set any parameter?
Upvotes: 3
Views: 1019
Reputation: 39052
You have to use the defined norm=norm
when plotting the contour plot img=plt.contourf(...)
. When used in the following way, both color bars are same
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both',
norm=norm) # <--- pass the norm here
Upvotes: 1