Colorbars and legends Outer and inset locations On-the-fly colorbars and legends Figure-wide colorbars and legends Added colorbar features Added legend features ,Proplot includes some useful changes to the matplotlib API that make working with colorbars and legends easier. Notable features include “inset” colorbars, “outer” legends, on-the-fly colorbars and legends, colorbars built from artists, and row-major and centered-row legends.,In proplot, you can add colorbars and legends on-the-fly by supplying keyword arguments to various PlotAxes commands. To plot data and draw a colorbar or legend in one go, pass a location (e.g., colorbar='r' or legend='b') to the plotting command (e.g., plot or contour). To pass keyword arguments to the colorbar and legend commands, use the legend_kw and colorbar_kw arguments (e.g., legend_kw={'ncol': 3}). Note that colorbar can also build colorbars from lists of arbitrary matplotlib artists, for example the lines generated by plot or line (see below).,Matplotlib supports drawing “inset” legends and “outer” colorbars using the loc and location keyword arguments. However, “outer” legends are only posssible using the somewhat opaque bbox_to_anchor keyword (see here) and “inset” colorbars are not possible without manually creating and positioning the associated axes. Proplot tries to improve this behavior:
[1]:
import proplot as pplt import numpy as np state = np.random.RandomState(51423) fig = pplt.figure(share = False, refwidth = 2.3) # Colorbars ax = fig.subplot(121, title = 'Axes colorbars') data = state.rand(10, 10) m = ax.heatmap(data, cmap = 'dusk') ax.colorbar(m, loc = 'r') ax.colorbar(m, loc = 't') # title is automatically adjusted ax.colorbar(m, loc = 'll', label = 'colorbar label') # inset colorbar demonstration # Legends ax = fig.subplot(122, title = 'Axes legends', titlepad = '0em') data = (state.rand(10, 5) - 0.5).cumsum(axis = 0) hs = ax.plot(data, lw = 3, cycle = 'ggplot', labels = list('abcde')) ax.legend(loc = 'll', label = 'legend label') # automatically infer handles and labels ax.legend(hs, loc = 't', ncols = 5, frame = False) # automatically infer labels from handles ax.legend(hs, list('jklmn'), loc = 'r', ncols = 1, frame = False) # manually override labels fig.format( abc = True, xlabel = 'xlabel', ylabel = 'ylabel', suptitle = 'Colorbar and legend location demo' )
[2]:
import proplot as pplt labels = list('xyzpq') state = np.random.RandomState(51423) fig = pplt.figure(share = 0, refwidth = 2.3, suptitle = 'On-the-fly colorbar and legend demo') # Legends data = (state.rand(30, 10) - 0.5).cumsum(axis = 0) ax = fig.subplot(121, title = 'On-the-fly legend') ax.plot(# add all at once data[: ,: 5], lw = 2, cycle = 'Reds1', cycle_kw = { 'ls': ('-', '--'), 'left': 0.1 }, labels = labels, legend = 'b', legend_kw = { 'title': 'legend title' } ) for i in range(5): ax.plot(# add one - by - one data[: , 5 + i], label = labels[i], linewidth = 2, cycle = 'Blues1', cycle_kw = { 'N': 5, 'ls': ('-', '--'), 'left': 0.1 }, colorbar = 'ul', colorbar_kw = { 'label': 'colorbar from lines' } ) # Colorbars ax = fig.subplot(122, title = 'On-the-fly colorbar') data = state.rand(8, 8) ax.contourf( data, cmap = 'Reds1', extend = 'both', colorbar = 'b', colorbar_kw = { 'length': 0.8, 'label': 'colorbar label' }, ) ax.contour( data, color = 'gray7', lw = 1.5, label = 'contour', legend = 'ul', legend_kw = { 'label': 'legend from contours' }, )
<matplotlib.contour.QuadContourSet at 0x7f995e6c7250>
[3]:
Simple, just plt.colorbar()
:
import numpy as np
import matplotlib.pyplot as plt
mat = np.random.random((10, 10))
plt.imshow(mat, origin = "lower", cmap = 'gray', interpolation = 'nearest')
plt.colorbar()
plt.show()
There's a builtin colorbar() function in pyplot. Here's an example using subplots:
fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plot = ax.pcolor(data) fig.colorbar(plot)
As usual, I figure it out right after I ask it ;). For posterity, here's my stab at it:
m = np.zeros((1, 20))
for i in range(20):
m[0, i] = (i * 5) / 100.0
print m
plt.imshow(m, cmap = 'gray', aspect = 2)
plt.yticks(np.arange(0))
plt.xticks(np.arange(0, 25, 5), [0, 25, 50, 75, 100])
plt.show()
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception.,The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset.,The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored.,For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs.
fig.colorbar(cm.ScalarMappable(norm = norm, cmap = cmap), ax = ax)
cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
Plot legends give meaning to a visualization, assigning meaning to the various plot elements. We previously saw how to create a simple legend; here we'll take a look at customizing the placement and aesthetics of the legend in Matplotlib.,I generally find in practice that it is clearer to use the first method, applying labels to the plot elements you'd like to show on the legend:,The simplest legend can be created with the plt.legend() command, which automatically creates a legend for any labeled plot elements:,This is a peek into the low-level artist objects that comprise any Matplotlib plot. If you examine the source code of ax.legend() (recall that you can do this with within the IPython notebook using ax.legend??) you'll see that the function simply consists of some logic to create a suitable Legend artist, which is then saved in the legend_ attribute and added to the figure when the plot is drawn.
import matplotlib.pyplot as plt
plt.style.use('classic')
% matplotlib inline
import numpy as np
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label = 'Sine')
ax.plot(x, np.cos(x), '--r', label = 'Cosine')
ax.axis('equal')
leg = ax.legend();
ax.legend(loc = 'upper left', frameon = False)
fig
ax.legend(frameon = False, loc = 'lower center', ncol = 2)
fig
ax.legend(fancybox = True, framealpha = 1, shadow = True, borderpad = 1) fig
Last Updated : 23 Nov, 2021,GATE CS 2021 Syllabus,GATE Live Course 2023
To install the matplotlib colorbar directly execute the following command on Jupyter Notebook or Visual Studio Code to get the results, Matplotlib-colorbar package is installed in order to generate using the colorbar argument. Here, matplotlib.pyplot is used to create a colorbar in a simpler way.
pip install matplotlib - colorbar