[Matplotlib-users] fixed colorbar position for repeated plots

Saito Kotaro (PSI) kotaro.saito at psi.ch
Tue May 8 12:14:11 EDT 2018


Dear Randy,

This might works.

-------------
fig, ax = plt.subplots()

# first time
data = np.clip(randn(250, 250), -1, 1)
img = ax.imshow(data, interpolation='nearest')
cbar = fig.colorbar(img, ticks=[-1, 0, 1])

# second time, reusing colorbar axis
data = 2*data
img = ax.imshow(data, interpolation='nearest')
cbar = fig.colorbar(img, cax=cbar.ax, ticks=[-1, 0, 1])

plt.show()
-------------

If you don’t specify cax, fig.colorbar automatically rip out a part of space used by original ax for new Axes object where Colorbar object sits in.
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.colorbar.html
That is why your code produce two colorbars.

I also modified some object names in your code.
There are many inappropriate colorbar examples which mix up object names such as cbar, cax and img.
ax.imshow returns AxesImage object and fig.colorbar make a colorbar from this AxesImage. That is why I name it img, not cax.
Then, first fig.colorbar rips out a space from the original Axes, make a new Axes for colorbar, instantiates, puts and returns a Colorbar object.
https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.colorbar
Colorbar object knows Axes object for itself (cbar.ax in my code). You can insert a line ”cax = cbar.ax" before second fig.colorbar and use “cax=cax”.

"2*data" in second plotting part is just to show that the second colorbar is properly produced without making new Axes.

Best regards,

Kotaro

//================//================//
Paul Scherrer Institut
Kotaro SAITO 斉藤耕太郎
Laboratory for Neutron Scattering and Imaging
WHGA/348
5232 Villigen PSI, Schweiz
+41 56 310 3179
kotaro.saito at psi.ch
https://sites.google.com/view/kotarosaito/
//================//================//

> On 2018/5/ 8, at 17:28, Heiland, Randy <heiland at iu.edu> wrote:
> 
> I have a script that lets a user step through and plot data in files and I want to fix the position, i.e. re-use, a single colorbar. How is this done? The following script illustrates the problem:
> 
> # adapted from https://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html
> import matplotlib.pyplot as plt
> import numpy as np
> from numpy.random import randn
> 
> fig, ax = plt.subplots()
> data = np.clip(randn(250, 250), -1, 1)
> cax = ax.imshow(data, interpolation='nearest')
> cbar = fig.colorbar(cax, ticks=[-1, 0, 1])
> 
> data = np.clip(randn(250, 250), -1, 1)
> cax = ax.imshow(data, interpolation='nearest')
> cbar = fig.colorbar(cax, ticks=[-1, 0, 1])
> 
> plt.show()
> 
> _______________________________________________
> Matplotlib-users mailing list
> Matplotlib-users at python.org
> https://mail.python.org/mailman/listinfo/matplotlib-users



More information about the Matplotlib-users mailing list