 # matplotlib normalize colorbar (python)

• Last Update :
• Techknowledgy :

Artists that map data to color pass the arguments vmin and vmax to construct a matplotlib.colors.Normalize() instance, then call it:,Matplotlib does this mapping in two steps, with a normalization from the input data to [0, 1] occurring first, and then mapping onto the indices in the colormap. Normalizations are classes defined in the matplotlib.colors() module. The default, linear normalization is matplotlib.colors.Normalize().,Objects that use colormaps by default linearly map the colors in the colormap from data values vmin to vmax. For example:, Colors Specifying Colors Customized Colorbars Tutorial Creating Colormaps in Matplotlib Colormap Normalization Choosing Colormaps in Matplotlib

pcm = ax.pcolormesh(x, y, Z, vmin = -1., vmax = 1., cmap = 'RdBu_r')
In: import matplotlib as mpl

In: norm = mpl.colors.Normalize(vmin = -1, vmax = 1)

In: norm(0)
Out: 0.5
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cbook as cbook
from matplotlib
import cm

N = 100
X, Y = np.mgrid[-3: 3: complex(0, N), -2: 2: complex(0, N)]

# A low hump with a spike coming out of the top right.Needs to have
# z / colour axis on a log scale so we see both hump and spike.linear
# scale only shows the spike.
Z1 = np.exp(-X ** 2 - Y ** 2)
Z2 = np.exp(-(X * 10) ** 2 - (Y * 10) ** 2)
Z = Z1 + 50 * Z2

fig, ax = plt.subplots(2, 1)

pcm = ax.pcolor(X, Y, Z,
norm = colors.LogNorm(vmin = Z.min(), vmax = Z.max()),
cmap = 'PuBu_r', shading = 'auto')
fig.colorbar(pcm, ax = ax, extend = 'max')

pcm = ax.pcolor(X, Y, Z, cmap = 'PuBu_r', shading = 'auto')
fig.colorbar(pcm, ax = ax, extend = 'max')
plt.show()
delta = 0.1
x = np.arange(-3.0, 4.001, delta)
y = np.arange(-4.0, 3.001, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X ** 2 - Y ** 2)
Z2 = np.exp(-(X - 1) ** 2 - (Y - 1) ** 2)
Z = (0.9 * Z1 - 0.5 * Z2) * 2

# select a divergent colormap
cmap = cm.coolwarm

fig, (ax1, ax2) = plt.subplots(ncols = 2)
pc = ax1.pcolormesh(Z, cmap = cmap)
fig.colorbar(pc, ax = ax1)
ax1.set_title('Normalize()')

pc = ax2.pcolormesh(Z, norm = colors.CenteredNorm(), cmap = cmap)
fig.colorbar(pc, ax = ax2)
ax2.set_title('CenteredNorm()')

plt.show()
N = 100
X, Y = np.mgrid[-3: 3: complex(0, N), -2: 2: complex(0, N)]
Z1 = np.exp(-X ** 2 - Y ** 2)
Z2 = np.exp(-(X - 1) ** 2 - (Y - 1) ** 2)
Z = (Z1 - Z2) * 2

fig, ax = plt.subplots(2, 1)

pcm = ax.pcolormesh(X, Y, Z,
norm = colors.SymLogNorm(linthresh = 0.03, linscale = 0.03,
vmin = -1.0, vmax = 1.0, base = 10),
cmap = 'RdBu_r', shading = 'auto')
fig.colorbar(pcm, ax = ax, extend = 'both')

pcm = ax.pcolormesh(X, Y, Z, cmap = 'RdBu_r', vmin = -np.max(Z), shading = 'auto')
fig.colorbar(pcm, ax = ax, extend = 'both')
plt.show()
N = 100
X, Y = np.mgrid[0: 3: complex(0, N), 0: 2: complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X ** 2

fig, ax = plt.subplots(2, 1, constrained_layout = True)

pcm = ax.pcolormesh(X, Y, Z1, norm = colors.PowerNorm(gamma = 0.5),
cmap = 'PuBu_r', shading = 'auto')
fig.colorbar(pcm, ax = ax, extend = 'max')
ax.set_title('PowerNorm()')

pcm = ax.pcolormesh(X, Y, Z1, cmap = 'PuBu_r', shading = 'auto')
fig.colorbar(pcm, ax = ax, extend = 'max')
ax.set_title('Normalize()')
plt.show()

Suggestion : 2

Please user the levels parameter, a set of examples:

In:

ndom
z = np.random.random((10, 10))

Without levels, colorbar will be auto-scaled

In :
plt.contourf(z)
plt.colorbar()
Out:
<matplotlib.colorbar.Colorbar at 0x120d47390>

In :
plt.contourf(z*2)
plt.colorbar()
Out:
<matplotlib.colorbar.Colorbar at 0x120f6ac10>

In :
plt.contourf(z, levels=np.linspace(0,2,20))
plt.colorbar()
Out:
<matplotlib.colorbar.Colorbar at 0x120dc3510>

I ran into this issue a while back and thought it was a bug (see MPL issue #5055). It's not, but it does require using the extend kwarg, which was non-intuitive to me. Here's what you want to do:

normi = mpl.colors.Normalize(vmin = -80, vmax = 20)

cont_PSD = plt.contourf(plotFreq, plotCoord, plotPxx,
np.linspace(-80, 20, 200),
linestyle = None,
norm = normi, extend = 'both')

plt.colorbar(colbar_PSD)

add this after plt.colorbar():

plt.clim(minimal_value, maximal_value)

for the contour plot, add the args vmin and vmax:

cont_PSD = plt.contourf(plotFreq, plotCoord, plotPxx, 200, linestyle = None, vmin = minimal_value, vmax = maximal_value)

You complete code should work like this :

import numpy as np;
import matplotlib as mpl;
import matplotlib.pyplot as plt;
[...]
plotFreq, plotCoord = np.meshgrid(plotFreqVect, plotCoordVect);

figHandler = plt.figure();
cont_PSD = plt.contourf(plotFreq, plotCoord, plotPxx, 200, linestyle = None, vmin = minimal_value, vmax = maximal_value);

plt.colorbar()
plt.clim(minimal_value, maximal_value)
plt.show()

Suggestion : 3

Demonstration of using norm to map colormaps onto data in non-linear ways.,Custom Norm: An example with a customized normalization. This one uses the example above, and normalizes the negative data differently from the positive.,Lognorm: Instead of pcolor log10(Z1) you can have colorbars that have the exponential labels using a norm.,SymLogNorm: two humps, one negative and one positive, The positive with 5-times the amplitude. Linearly, you cannot see detail in the negative hump. Here we logarithmically scale the positive and negative data separately.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.mlab
import bivariate_normal
N = 100
X, Y = np.mgrid[-3: 3: complex(0, N), -2: 2: complex(0, N)]

# A low hump with a spike coming out of the top right.Needs to have
# z / colour axis on a log scale so we see both hump and spike.linear
# scale only shows the spike.

Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + \
0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)

fig, ax = plt.subplots(2, 1)

pcm = ax.pcolor(X, Y, Z1,
norm = colors.LogNorm(vmin = Z1.min(), vmax = Z1.max()),
cmap = 'PuBu_r')
fig.colorbar(pcm, ax = ax, extend = 'max')

pcm = ax.pcolor(X, Y, Z1, cmap = 'PuBu_r')
fig.colorbar(pcm, ax = ax, extend = 'max')
X, Y = np.mgrid[0: 3: complex(0, N), 0: 2: complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X ** (2.)

fig, ax = plt.subplots(2, 1)

pcm = ax.pcolormesh(X, Y, Z1, norm = colors.PowerNorm(gamma = 1. / 2.),
cmap = 'PuBu_r')
fig.colorbar(pcm, ax = ax, extend = 'max')

pcm = ax.pcolormesh(X, Y, Z1, cmap = 'PuBu_r')
fig.colorbar(pcm, ax = ax, extend = 'max')
X, Y = np.mgrid[-3: 3: complex(0, N), -2: 2: complex(0, N)]
Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0)) ** 2\ -
0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0)) ** 2
Z1 = Z1 / 0.03

fig, ax = plt.subplots(2, 1)

pcm = ax.pcolormesh(X, Y, Z1,
norm = colors.SymLogNorm(linthresh = 0.03, linscale = 0.03,
vmin = -1.0, vmax = 1.0),
cmap = 'RdBu_r')
fig.colorbar(pcm, ax = ax, extend = 'both')

pcm = ax.pcolormesh(X, Y, Z1, cmap = 'RdBu_r', vmin = -np.max(Z1))
fig.colorbar(pcm, ax = ax, extend = 'both')
X, Y = np.mgrid[-3: 3: complex(0, N), -2: 2: complex(0, N)]
Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0)) ** 2\ -
0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0)) ** 2
Z1 = Z1 / 0.03

# Example of making your own norm.Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:

class MidpointNormalize(colors.Normalize):
def __init__(self, vmin = None, vmax = None, midpoint = None, clip = False):
self.midpoint = midpoint
colors.Normalize.__init__(self, vmin, vmax, clip)

def __call__(self, value, clip = None):
# I 'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
# # # # #
fig, ax = plt.subplots(2, 1)

pcm = ax.pcolormesh(X, Y, Z1,
norm = MidpointNormalize(midpoint = 0.),
cmap = 'RdBu_r')
fig.colorbar(pcm, ax = ax, extend = 'both')

pcm = ax.pcolormesh(X, Y, Z1, cmap = 'RdBu_r', vmin = -np.max(Z1))
fig.colorbar(pcm, ax = ax, extend = 'both')
fig, ax = plt.subplots(3, 1, figsize = (8, 8))
ax = ax.flatten()
# even bounds gives a contour - like effect
bounds = np.linspace(-1, 1, 10)
norm = colors.BoundaryNorm(boundaries = bounds, ncolors = 256)
pcm = ax.pcolormesh(X, Y, Z1,
norm = norm,
cmap = 'RdBu_r')
fig.colorbar(pcm, ax = ax, extend = 'both', orientation = 'vertical')

# uneven bounds changes the colormapping:
bounds = np.array([-0.25, -0.125, 0, 0.5, 1])
norm = colors.BoundaryNorm(boundaries = bounds, ncolors = 256)
pcm = ax.pcolormesh(X, Y, Z1, norm = norm, cmap = 'RdBu_r')
fig.colorbar(pcm, ax = ax, extend = 'both', orientation = 'vertical')

pcm = ax.pcolormesh(X, Y, Z1, cmap = 'RdBu_r', vmin = -np.max(Z1))
fig.colorbar(pcm, ax = ax, extend = 'both', orientation = 'vertical')

plt.show()

Suggestion : 4

Please note that one should not use ax.imshow(norm(image)) because the colorbar ticks marks will represent normalized image values (on a linear scale), not the actual image values. Also, the image displayed by ax.imshow(norm(image)) is not exactly equivalent to ax.imshow(image, norm=norm) if the image contains NaN or inf values. The exact equivalent is ax.imshow(norm(np.ma.masked_invalid(image)).,While this is the simplest case, it is also possible for a completely different image to be used to establish the normalization (e.g. if one wants to display several images with exactly the same normalization and stretch).,Stretches can also be combined with other stretches, just like transformations. The resulting CompositeStretch can be used to normalize Matplotlib images like any other stretch. For example, a composite stretch can stretch residual images with negative values:,The astropy.visualization module provides a framework for transforming values in images (and more generally any arrays), typically for the purpose of visualization. Two main types of transformations are provided:

import numpy as np
import matplotlib.pyplot as plt
from astropy.visualization
import simple_norm

# Generate a test image
image = np.arange(65536).reshape((256, 256))

# Create an ImageNormalize object
norm = simple_norm(image, 'sqrt')

# Display the image
fig = plt.figure()
im = ax.imshow(image, origin = 'lower', norm = norm)
fig.colorbar(im)
>>> from astropy.visualization
import MinMaxInterval
>>>
interval = MinMaxInterval()
>>> interval.get_limits([1, 3, 4, 5, 6])
(1, 6)
>>> interval([1, 3, 4, 5, 6])
array([0., 0.4, 0.6, 0.8, 1.])
>>> from astropy.visualization
import PercentileInterval
>>>
interval = PercentileInterval(50.) >>>
interval.get_limits([1, 3, 4, 5, 6])
(3.0, 5.0) >>>
interval([1, 3, 4, 5, 6]) #
default is clip = True
array([0., 0., 0.5, 1., 1.]) >>>
interval([1, 3, 4, 5, 6], clip = False)
array([-1., 0., 0.5, 1., 1.5])
>>> from astropy.visualization
import SqrtStretch
>>>
stretch = SqrtStretch() >>>
stretch([0., 0.25, 0.5, 0.75, 1.])
array([0., 0.5, 0.70710678, 0.8660254, 1.])

Suggestion : 5

import parula as par
import matplotlib
from matplotlib
import cm
import numpy as np

magma_cmap = matplotlib.cm.get_cmap('magma')
viridis_cmap = matplotlib.cm.get_cmap('viridis')
parula_cmap = par.parula_map

viridis_rgb = []
magma_rgb = []
parula_rgb = []
norm = matplotlib.colors.Normalize(vmin = 0, vmax = 255)

for i in range(0, 255):
k = matplotlib.colors.colorConverter.to_rgb(magma_cmap(norm(i)))
magma_rgb.append(k)

for i in range(0, 255):
k = matplotlib.colors.colorConverter.to_rgb(viridis_cmap(norm(i)))
viridis_rgb.append(k)

for i in range(0, 255):
k = matplotlib.colors.colorConverter.to_rgb(parula_cmap(norm(i)))
parula_rgb.append(k)

def matplotlib_to_plotly(cmap, pl_entries):
h = 1.0 / (pl_entries - 1)
pl_colorscale = []

for k in range(pl_entries):
C = map(np.uint8, np.array(cmap(k * h)[: 3]) * 255)
pl_colorscale.append([k * h, 'rgb' + str((C, C, C))])

return pl_colorscale

magma = matplotlib_to_plotly(magma_cmap, 255)
viridis = matplotlib_to_plotly(viridis_cmap, 255)
parula = matplotlib_to_plotly(parula_cmap, 255)
import plotly.plotly as py
import numpy as np
import os
import plotly.graph_objs as go
from plotly
import tools

def heatmap_plot(colorscale, title):
example_dir = os.path.join(os.path.dirname('__file__'), "examples")

trace1 = go.Heatmap(z = hist2d, colorscale = colorscale, showscale = False)

"st-helens_before-modified.txt.gz")).T
trace2 = go.Heatmap(z = st_helens, colorscale = colorscale, y0 = -5, x0 = -5)

dx = dy = 0.05
y, x = np.mgrid[-5: 5 + dy: dy, -5: 10 + dx: dx]
z = np.sin(x) ** 10 + np.cos(10 + y * x) + np.cos(x) + 0.2 * y + 0.1 * x
trace3 = go.Heatmap(z = z, colorscale = colorscale, showscale = False)

fig = tools.make_subplots(rows = 1, cols = 3, print_grid = False)
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 2)
fig.append_trace(trace3, 1, 3)
fig['layout'].update(title = title)
fig['layout']['xaxis2'].update(range = [0, 450])
fig['layout']['yaxis2'].update(range = [0, 270])

return fig
py.iplot(heatmap_plot(colorscale = magma, title = 'MAGMA'))
py.iplot(heatmap_plot(colorscale = viridis, title = 'VIRIDIS'))
py.iplot(heatmap_plot(colorscale = parula, title = 'PARULA'))
import plotly.plotly as py
from plotly.tools
import FigureFactory as FF
import plotly.graph_objs as go
import numpy as np
from scipy.spatial
import Delaunay

u = np.linspace(0, 2 * np.pi, 24)
v = np.linspace(-1, 1, 8)
u, v = np.meshgrid(u, v)
u = u.flatten()
v = v.flatten()

tp = 1 + 0.5 * v * np.cos(u / 2.)
x = tp * np.cos(u)
y = tp * np.sin(u)
z = 0.5 * v * np.sin(u / 2.)

points2D = np.vstack([u, v]).T
tri = Delaunay(points2D)
simplices = tri.simplices

trace1 = FF.create_trisurf(x = x, y = y, z = z,
simplices = simplices, colormap = magma_rgb, plot_edges = False,
title = 'Magma Colorscale for Trisurf Plot')
py.iplot(trace1)