Matplotlib.pyplot.colorbar() function in Python - GeeksforGeeks

11 Dec, 2020
Colorbars are a visualization of the mapping from scalar values to colors. In Matplotlib they are drawn into a dedicated axis.
Note: Colorbars are typically created through Figure.colorbar or its pyplot wrapper pyplot.colorbar, which uses make_axes and Colorbar internally. As an end-user, you most likely won’t have to call the methods or instantiate the classes in this module explicitly.
The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale.
Syntax:matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwarg)
Parameters:
ax: This parameter is an optional parameter and it contains Axes or list of Axes.
**kwarg(keyword arguments): This parameter is an optional parameter and are of two kinds:   
colorbar properties:
extend:{‘neither’, ‘both’, ‘min’, ‘max’} makes pointed end(s) for out-of-rangevalues.   
label:The label on the colorbar’s long axis.  
ticks:None or list of ticks or Locator.     
Returns:colorbar which is an instance of the class ‘matplotlib.colorbar.Colorbar’.      
Below examples illustrate the matplotlib.pyplot.colorbar() function in matplotlib.pyplot:
Example #1: To Add a horizontal colorbar to a scatterplot.
Python3
# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib.pyplot as plt  # Dataset# List of total number of items purchased # from each productspurchaseCount = [100, 200, 150, 23, 30, 50,                 156, 32, 67, 89]  # List of total likes of 10 productslikes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45]  # List of Like/Dislike ratio of 10 productsratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56,          1.28, 1.09, 1.02]  # scatterplotplt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer")  plt.colorbar(label="Like/Dislike Ratio", orientation="horizontal")plt.show()
Output:
Example #2: To Add a single colorbar to multiple subplots.
Python3
# Python Program illustrating# pyplot.colorbar() methodimport matplotlib.pyplot as plt  # creates four Axesfig, axes = plt.subplots(nrows=2, ncols=2)  for ax in axes.flat:    im = ax.imshow(np.random.random((10, 10)), vmin=0, vmax=1)  plt.colorbar(im, ax=axes.ravel().tolist())  plt.show()
Output:
Example #3: To Add colorbar to a non-mappable object.
Python3
# Python Program illustrating# pyplot.colorbar() methodimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt  x = np.linspace(0, 5, 100)N = 7  # colormapcmap = plt.get_cmap('jet', N)  fig, ax1 = plt.subplots(1, 1, figsize=(8, 6))  for i, n in enumerate(np.linspace(0, 2, N)):    y = x*i+n    ax1.plot(x, y, c=cmap(i))  plt.xlabel('x-axis')plt.ylabel('y-axis')  # Normalizernorm = mpl.colors.Normalize(vmin=0, vmax=2)  # creating ScalarMappablesm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)sm.set_array([])  plt.colorbar(sm, ticks=np.linspace(0, 2, N))    plt.show()
Output:
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists