1

I have a matplotlib bar chart, which bars are colored according to some rules through a colormap. I need a colorbar on the right of the main axes, so I added a new axes with

fig, (ax, ax_cbar) = plt.subplots(1,2)

and managed to draw my color bar in the ax_bar axes, while I have my data displayed in the ax axes. Now I need to reduce the width of the ax_bar, because it looks like this: enter image description here

How can I do?

Davide Tamburrino
  • 581
  • 1
  • 5
  • 11

2 Answers2

2

Using subplots will always divide your figure equally. You can manually divide up your figure in a number of ways. My preferred method is using subplot2grid.

In this example, we are setting the figure to have 1 row and 10 columns. We then set ax to be the start at row,column = (0,0) and have a width of 9 columns. Then set ax_cbar to start at (0,9) and has by default a width of 1 column.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,6))

num_columns = 10
ax = plt.subplot2grid((1,num_columns), (0,0), colspan=num_columns-1)
ax_cbar = plt.subplot2grid((1,num_columns), (0,num_columns-1))
James
  • 32,991
  • 4
  • 47
  • 70
2

The ususal way to add a colorbar is by simply putting it next to the axes:

fig.colorbar(sm)

where fig is the figure and sm is the scalar mappable to which the colormap refers. In the case of the bars, you need to create this ScalarMappable yourself. Apart from that there is no need for complex creation of multiple axes.

import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np

fig , ax = plt.subplots()

x = [0,1,2,3]
y = np.array([34,40,38,50])*1e3
norm = matplotlib.colors.Normalize(30e3, 60e3)
ax.bar(x,y, color=plt.cm.plasma_r(norm(y)) )
ax.axhline(4.2e4, color="gray")
ax.text(0.02, 4.2e4, "42000", va='center', ha="left", bbox=dict(facecolor="w",alpha=1),
        transform=ax.get_yaxis_transform())

sm = plt.cm.ScalarMappable(cmap=plt.cm.plasma_r, norm=norm)
sm.set_array([])

fig.colorbar(sm)
plt.show()

enter image description here


If you do want to create a special axes for the colorbar yourself, the easiest method would be to set the width already inside the call to subplots:

fig , (ax, cax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios" : [10,1]})

and later put the colorbar to the cax axes,

fig.colorbar(sm, cax=cax)


Note that the following questions have been asked for this homework assignment already:
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Was using `width_ratios` with multiple seaboard heat maps. There, I guess this is the easiest approach. Excellent answer. – Quickbeam2k1 Aug 17 '20 at 14:26