Matplotlib.colors.BoundaryNorm class in Python - GeeksforGeeks

19 Oct, 2021
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. 
The matplotlib.colors.BoundaryNorm class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.The matplotlib.colors.BoundaryNorm class is used to create a colormap based on discrete intervals. BoundaryNorm maps values to integers, unlike Normalize or LogNorm which does mapping to the interval of 0 to 1. Piecewise linear interpolation can be used for mapping to the o- interval, however, using integers is simpler and leads to the reduction of the number of conversions back and forth among integer and floating points.Parameters:  
boundaries: it is an array like object that monotonically increase sequence of boundaries ncolor: It accepts an integer value that represents a number of colors in the colormap that will be used. clip: It accepts a boolean value and is a optional parameter. If the clip is True, the values that are out of range and they are below the boundaries[0] are mapped to 0, whereas if they are above the boundaries[-1] they are mapped to ncolors-1. If the clip is set to False, the out of range values and they are below the boundaries[0] are mapped to -1, whereas if they are above boundaries[-1], they are mapped to ncolors. The Colormap.__call__() convert these into valid indices.  
boundaries: it is an array like object that monotonically increase sequence of boundaries 
ncolor: It accepts an integer value that represents a number of colors in the colormap that will be used. 
clip: It accepts a boolean value and is a optional parameter. If the clip is True, the values that are out of range and they are below the boundaries[0] are mapped to 0, whereas if they are above the boundaries[-1] they are mapped to ncolors-1. If the clip is set to False, the out of range values and they are below the boundaries[0] are mapped to -1, whereas if they are above boundaries[-1], they are mapped to ncolors. The Colormap.__call__() convert these into valid indices.  
Note: The edges of bins are defined by boundaries and the data falling within the bins are mapped to the same color index. If the ncolors are not equal to the number of bins, linear interpolation is used to choose color for them. Example 1:  
Python3
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.collections import LineCollectionfrom matplotlib.colors import ListedColormap, BoundaryNorm a = np.linspace(0, 3 * np.pi, 500)b = np.sin(a)# this is the first derivativedbda = np.cos(0.5 * (a[:-1] + a[1:]))  # Creating  line segments so# to color them individuallypoints = np.array([a, b]).T.reshape(-1, 1, 2)set_of_segments = np.concatenate([points[:-1],                                  points[1:]],                                 axis = 1) figure, axes = plt.subplots(2, 1,                            sharex = True,                            sharey = True) # Mapping the data points with# continuous normcontinuous_norm = plt.Normalize(dbda.min(),                               dbda.max()) line_collection = LineCollection(set_of_segments,                                 cmap ='viridis',                                 norm = continuous_norm) # Set the values used for# colormappingline_collection.set_array(dbda)line_collection.set_linewidth(2)line = axes[0].add_collection(line_collection)figure.colorbar(line, ax = axes[0]) # Use a boundary norm insteadcmap = ListedColormap(['r', 'g', 'b'])boundary_norm = BoundaryNorm([-1, -0.5, 0.5, 1],                             cmap.N) line_collection = LineCollection(set_of_segments,                                 cmap = cmap,                                 norm = boundary_norm) line_collection.set_array(dbda)line_collection.set_linewidth(2)line = axes[1].add_collection(line_collection)figure.colorbar(line, ax = axes[1]) axes[0].set_xlim(a.min(), a.max())axes[0].set_ylim(-1.1, 1.1)plt.show()
Output:  
Example 2:  
Python3
import numpy as npimport matplotlib as mplimport matplotlib.pylab as plt  # setup the plotfigure, axes = plt.subplots(1, 1,                            figsize=(6, 6)) # defining random datax = np.random.rand(20)y = np.random.rand(20) tag = np.random.randint(0, 20, 20)tag[10:12] = 0 # defining the colormapcmap = plt.cm.jet  # extracting all colorscmaplist = [cmap(i) for i in range(cmap.N)] # making first color entry  greycmaplist[0] = (.5, .5, .5, 1.0) # new mapcmap = mpl.colors.LinearSegmentedColormap.from_list(   'Custom cmap', cmaplist, cmap.N) # defining the bins and normsbounds = np.linspace(0, 20, 21)norm = mpl.colors.BoundaryNorm(bounds,                               cmap.N) # the scatterscat = axes.scatter(x, y, c=tag,                    s=np.random.randint(100,                                        500,                                        20),                    cmap=cmap, norm=norm) # axes for the colorbarax2 = figure.add_axes([0.95, 0.1,                       0.03, 0.8])  axes.set_title(' discrete colors')
Output: 
 
gabaa406
sweetyty
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java