colorbar() accepts a cax keyword argument that allows you to specify the axes object that the colorbar will be drawn on.

In your case, you would change your colorbar call to the following:

# colorbar
axes = plt.subplot2grid((4, 2), (0, 1), rowspan=3)
plt.colorbar(pc, cax=axes)

This will take up the whole space given by subplot2grid; you can adjust this to be more reasonable either by having the main axes take up many more columns than the colorbar axes, or by setting up the gridspec explicitly. For example, your figure may be easier to tweak with the following:

from matplotlib import gridspec
gs = gridspec.GridSpec(2, 2, height_ratios=(3, 1), width_ratios=(9, 1))

# first graph
axes = plt.subplot(gs[0,0])
pc = plt.pcolor(df1, cmap='jet')

# second graph
axes = plt.subplot(gs[1,0])
plt.pcolor(df2, cmap='Greys')

# colorbar
axes = plt.subplot(gs[0,1])
plt.colorbar(pc, cax=axes)

Then you can just change height_ratios and width_ratios to your liking.

Answer from tbekolay on Stack Overflow
🌐
Matplotlib
matplotlib.org › stable › api › _as_gen › matplotlib.pyplot.colorbar.html
matplotlib.pyplot.colorbar — Matplotlib 3.11.2 documentation
This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image.
🌐
Matplotlib
matplotlib.org › stable › gallery › images_contours_and_fields › pcolor_demo.html
pcolor images — Matplotlib 3.11.2 documentation
Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z, shading='auto', norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap='PuBu_r', shading='auto') fig.colorbar(c, ax=ax1) plt.show() References ·
🌐
Matplotlib
matplotlib.org › stable › users › explain › axes › colorbar_placement.html
Placing colorbars — Matplotlib 3.11.2 documentation
We do this by passing Figure.colorbar a list of Axes with the ax kwarg. fig, axs = plt.subplots(2, 2) cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col]) fig.colorbar(pcm, ax=axs[:, col], shrink=0.6)
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-plot-a-pcolor-colorbar-in-a-different-subplot-in-matplotlib
How to plot a pcolor colorbar in a different subplot in Matplotlib?
July 7, 2021 - To plot a pcolor colorbar in a different subplot in Matplotlib, you can create multiple subplots and add individual colorbars to each one using the fig.colorbar() method.
🌐
Matplotlib
matplotlib.org › 3.1.1 › gallery › images_contours_and_fields › pcolor_demo.html
Pcolor Demo — Matplotlib 3.1.2 documentation
May 1, 2020 - Z1 = np.exp(-(X)**2 - (Y)**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z, norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap='PuBu_r') fig.colorbar(c, ax=ax1) ...
🌐
GeeksforGeeks
geeksforgeeks.org › matplotlib-pyplot-pcolor-function-in-python
Matplotlib.pyplot.pcolor() function in Python - GeeksforGeeks
November 25, 2020 - Z1 = np.exp(-(X)**2 - (Y)**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z,norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap=plt.cm.autumn) fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap=plt.cm.autumn) fig.colorbar(c, ax=ax1) plt.show() Output: Comment · More infoAdvertise with us · Next Article · Matplotlib.pyplot.pcolor() function in Python ·
🌐
Matplotlib
matplotlib.org › stable › gallery › subplots_axes_and_figures › colorbar_placement.html
Placing Colorbars — Matplotlib 3.7.2 documentation
April 13, 2022 - The simplest case is just attaching a colorbar to each axes: import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) fig, axs = plt.subplots(2, 2) cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cmaps[col]) fig.colorbar(pcm, ax=ax)
🌐
Stack Overflow
stackoverflow.com › questions › 44311426 › python-pcolor-and-colorbar-dont-use-the-whole-colormap
Python pcolor and colorbar dont use the whole colormap - Stack Overflow
When I try to create a simple pcolor plot with values between -2 and 10 the default pcolor and colorbar use the colormap only from -2 to 2, thus showing wrong colors. Here is a working example: import numpy as np from matplotlib import pyplot as plt m = np.array([[ 0.9, 2., 2., 1.8], [ -0.8, 0.1, -0.6, -2], [ -0.1, -2, -2, -0.06], [ 3, 4, 7, 10]]) x = [0, 1, 2, 3] y = [0, 1, 2, 3] xv,yv = np.meshgrid(x,y) fig = plt.figure() ax = fig.add_subplot(111) print m.min(),m.max() cax = ax.pcolormesh(xv,yv,m, cmap='viridis') cbar = fig.colorbar(cax) plt.show() I would include an image but dont have enough reputation on stackoverflow ·
Find elsewhere
🌐
pythontutorials
pythontutorials.net › blog › how-to-plot-pcolor-colorbar-in-a-different-subplot-matplotlib
How to Plot Matplotlib pcolor Colorbar in a Different Subplot Without Empty Graphs — pythontutorials.net
By default, when you call plt.colorbar(), Matplotlib attaches the colorbar to the current axis (Axes object) and resizes the plot to make space. But if you want the colorbar in a separate subplot (e.g., to the right of your pcolor plot), naively ...
🌐
Matplotlib
matplotlib.org › stable › gallery › images_contours_and_fields › pcolormesh_levels.html
pcolormesh — Matplotlib 3.11.2 documentation
# Therefore, remove the last value from the z array. z = z[:-1, :-1] levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max()) # pick the desired colormap, sensible levels, and define a normalization # instance which takes data values and translates those into levels. cmap = plt.colormaps['PiYG'] norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) fig, (ax0, ax1) = plt.subplots(nrows=2) im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm) fig.colorbar(im, ax=ax0) ax0.set_title('pcolormesh with levels') # contours are *point* based plots, so convert our bound into point # centers cf = ax1.contourf(x[:-1, :-1] + dx/2., y[:-1, :-1] + dy/2., z, levels=levels, cmap=cmap) fig.colorbar(cf, ax=ax1) ax1.set_title('contourf with levels') # adjust spacing between subplots so `ax1` title and `ax0` tick labels # don't overlap fig.tight_layout() plt.show() References ·
🌐
Matplotlib
matplotlib.org › stable › gallery › color › colorbar_basics.html
Colorbar — Matplotlib 3.11.2 documentation
cbar = fig.colorbar(pos_neg_clipped, ax=ax3, extend='both') cbar.minorticks_on() plt.show()
🌐
Matplotlib
matplotlib.org › 3.4.2 › gallery › images_contours_and_fields › pcolor_demo.html
Pcolor Demo — Matplotlib 3.4.2 documentation
May 8, 2021 - Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z, shading='auto', norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap='PuBu_r', shading='auto') ...
🌐
Matplotlib
matplotlib.org › 3.2.1 › gallery › images_contours_and_fields › pcolor_demo.html
Pcolor Demo — Matplotlib 3.2.1 documentation
April 8, 2020 - Z1 = np.exp(-(X)**2 - (Y)**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z, norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap='PuBu_r') fig.colorbar(c, ax=ax1) ...
🌐
Matplotlib
matplotlib.org › stable › api › _as_gen › matplotlib.pyplot.pcolor.html
matplotlib.pyplot.pcolor — Matplotlib 3.11.2 documentation
matplotlib.pyplot.pcolor(*args, shading=None, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, colorizer=None, data=None, **kwargs)[source]#
🌐
Matplotlib
matplotlib.org › 2.0.2 › examples › pylab_examples › pcolor_demo.html
pylab_examples example code: pcolor_demo.py — Matplotlib 2.0.2 documentation
# Therefore, remove the last value ... y, z, cmap='RdBu', vmin=z_min, vmax=z_max) plt.title('pcolor') # set the limits of the plot to the limits of the data plt.axis([x.min(), x.max(), y.min(), y.max()]) plt.colorbar() plt.subplot(2, 2, 2) plt.pcolormesh(x, y, z, cmap='RdBu', ...
Top answer
1 of 4
194
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

2 of 4
9

This will make you add label and change colorbar's tick and label size:

clb=plt.colorbar()
clb.ax.tick_params(labelsize=8) 
clb.ax.set_title('Your Label',fontsize=8)

This can be also used if you have sublots:

plt.tight_layout()
plt.subplots_adjust(bottom=0.05)
cax = plt.axes([0.1, 0, 0.8, 0.01]) #Left,bottom, length, width
clb=plt.colorbar(cax=cax,orientation="horizontal")
clb.ax.tick_params(labelsize=8) 
clb.ax.set_title('Your Label',fontsize=8)
🌐
Matplotlib
matplotlib.org › 3.3.1 › gallery › images_contours_and_fields › pcolor_demo.html
Pcolor Demo — Matplotlib 3.3.1 documentation
August 14, 2020 - Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z, shading='auto', norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap='PuBu_r', shading='auto') ...
🌐
Xarray
docs.xarray.dev › en › latest › generated › xarray.plot.pcolormesh.html
xarray.plot.pcolormesh
yincrease (None, True, or False, optional) – Should the values on the y axis be increasing from top to bottom? If None, use the default for the Matplotlib function. add_colorbar (bool, optional) – Add colorbar to axes.