A colorbar is a bar that runs alongside the facet of a Matplotlib chart and acts as a legend for the colours proven within the chart.
Matplotlib presentations colorbars at the proper facet of a chart through default, however you’ll be able to simply alternate this through the use of purposes from the Matplotlib AxesGrid toolkit.
This instructional displays a number of examples of the way to virtue those purposes in follow.
Instance 1: Place Colorbar on Proper Facet of Chart
Please see code displays the way to generate a Matplotlib chart and the way to playground a colorbar at the proper facet of the chart:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable #build this case reproducible np.random.seed(1) #develop chart fig, ax = plt.subplots() im = ax.imshow(np.random.rand(15,15)) ax.set_xlabel('x-axis label') #upload colour bar fig.colorbar(im) plt.display()
Instance 2: Place Colorbar Beneath Chart
Please see code displays the way to playground a colorbar beneath a Matplotlib chart:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable #build this case reproducible np.random.seed(1) #develop chart fig, ax = plt.subplots() im = ax.imshow(np.random.rand(15,15)) ax.set_xlabel('x-axis label') #upload colour bar beneath chart divider = make_axes_locatable(ax) cax = divider.new_vertical(dimension="5%", residence=0.6, pack_start=True) fig.add_axes(cax) fig.colorbar(im, cax=cax, orientation='horizontal') plt.display()
Be aware that theĀ residenceĀ argument creates padding between the x-axis of the chart and the colorbar. The upper the price for residence, the additional away the colorbar will probably be from the x-axis.
Instance 3: Place Colorbar Above Chart
Please see code displays the way to playground a colorbar above a Matplotlib chart:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable #build this case reproducible np.random.seed(1) #develop chart fig, ax = plt.subplots() im = ax.imshow(np.random.rand(15,15)) ax.set_xlabel('x-axis label') #upload colour bar beneath chart divider = make_axes_locatable(ax) cax = divider.new_vertical(dimension="5%", residence=0.4) fig.add_axes(cax) fig.colorbar(im, cax=cax, orientation='horizontal') plt.display()
You’ll to find extra Matplotlib tutorials right here.