Thursday, December 26, 2024
Google search engine
HomeLanguagesMatplotlib.colors.from_levels_and_colors() in Python

Matplotlib.colors.from_levels_and_colors() in Python

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.

matplotlib.colors.from_levels_and_colors()

The matplotlib.colors.from_levels_and_colors() function is a helper function that helps create cmap and norm instance whose behavior is similar to that of contourf’s levels and colors argument.

Syntax: matplotlib.colors.from_levels_and_colors(levels, colors, extend=’neither’) 

Parameters:

  1. levels: It is a sequence of numbers that represent quantization levels that are used to construct the BoundaryNorm. A value v is quantized to level k if lev[k] <= v < lev[k+1].
  2. colors: It is a sequence of colors that are used as fill colors for each level. There must be n_level – 1 colors if extend is “neither”. Add one extra color for an extend of “min” or “max” and for an extend of “both” add two colors.
  3. extend: It is an optional parameter that accepts one of the four values namely ‘neither’, ‘min’, ‘max’ or ‘both’.

Return Type : This function returns a Normalized cmap and a colormap norm

Example 1: 

Python3




import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
 
data1 = 3 * np.random.random((10, 10))
data2 = 5 * np.random.random((10, 10))
 
levels = [0, 1, 2, 3, 4, 5]
colors = ['red', 'brown',
          'yellow', 'green',
          'blue']
cmap, norm = matplotlib.colors.from_levels_and_colors(levels,
                                                      colors)
 
fig, axes = plt.subplots(ncols = 2)
 
for ax, data in zip(axes, [data1, data2]):
    im = ax.imshow(dat,
                   cmap = cmap,
                   norm = norm,
                   interpolation ='none')
     
    fig.colorbar(im, ax = ax, orientation ='horizontal')
     
plt.show()


Output:

  

Example 2: 

Python3




import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import from_levels_and_colors
 
nvals = np.random.randint(2, 20)
data = np.random.randint(0, nvals,
                         (10, 10))
 
colors = np.random.random((nvals, 3))
# Make the colors pastels...
colors = colors / 2.5 + 0.55
 
levels = np.arange(nvals + 1) - 0.5
cmap, norm = from_levels_and_colors(levels,
                                    colors)
 
fig, ax = plt.subplots()
im = ax.imshow(data,
               interpolation ='nearest',
               cmap = cmap,
               norm = norm)
 
fig.colorbar(im, ticks = np.arange(nvals))
plt.show()


Output:

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments