Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I place a vertical colorbar to the left of the plot in matplotlib?

From the matplotlib command summary for the colorbar method I am aware that the keyword argument orientation := 'horizontal' | 'vertical' as a parameter places an horizontal bar underneath the plot or a vertical to the right of it respectively.

Yet, in my situation, I would rather place the colour bar at the opposite side of the default (without too much fiddling... if possible).

How could I code this? Am I missing some obvious feature?

like image 962
XavierStuvw Avatar asked May 17 '16 15:05

XavierStuvw


People also ask

How do I change the position of the color bar in Matplotlib?

The position of the Matplotlib color bar can be changed according to our choice by using the functions from Matplotlib AxesGrid Toolkit. The placing of inset axes is similar to that of legend, the position is modified by providing location options concerning the parent box. Axes into which the colorbar will be drawn.

How do I change the location of my color bar?

To move the colorbar to a different tile, set the Layout property of the colorbar. To display the colorbar in a location that does not appear in the table, use the Position property to specify a custom location. If you set the Position property, then MATLAB sets the Location property to 'manual' .

What is the Matplotlib Pyplot function that plots a Colorbar on the side of a plot?

The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale.


2 Answers

I've found another method that avoids having to manually edit axes locations, and instead allows you to keep the colorbar linked to an existing plot axis by using the location keyword (method adapted initially from here).

The location argument is meant to be used on colorbars which reference multiple axes in a list (and will throw an error if colorbar is given only one axis), but if you simply put your one axis in a list, it will allow you to use the argument. You can use the following code as an example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
axp = ax.imshow(np.random.randint(0, 100, (100, 100)))
cb = plt.colorbar(axp,ax=[ax],location='left')
plt.show()

which yields this plot:

plot:

like image 63
jgholder Avatar answered Oct 13 '22 06:10

jgholder


I think the easiest way is to make sure the colorbar is in its own axis. You can adapt from this example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
axp = ax.imshow(np.random.randint(0, 100, (100, 100)))
# Adding the colorbar
cbaxes = fig.add_axes([0.1, 0.1, 0.03, 0.8])  # This is the position for the colorbar
cb = plt.colorbar(axp, cax = cbaxes)
plt.show()

which results in this:

Matplotlib colorbar on the left side of plot

like image 31
armatita Avatar answered Oct 13 '22 06:10

armatita