3

I'm losing my wits here with this 'simple' problem:

In the colorbar (illustrated in picture) in matplotlib I need to move offsetText (base multiplier) from top of the colorbar to bottom.

Code that I'm using for this plot is (using gridspec):

f.add_subplot(ax12)

ax10 = plt.Subplot(f, gs00[1, 0])
cb = plt.colorbar(h3,cax=ax10)
cb.formatter.set_scientific(True)
cb.formatter.set_powerlimits((0,0))
cb.ax.yaxis.offsetText.set(size=6)
cb.update_ticks()

ax10.yaxis.set_ticks_position('left')
ax10.tick_params(labelsize=6)
f.add_subplot(ax10)

Thanks in advance! (Btw, Python version = 2.7.6, matplotlib version = 1.3.1 - upgrading currently not an option until I finish current project)

enter image description here

  • What part of your code is the "1e5" coming from? – blubberdiblub May 01 '17 at 11:43
  • I m doing scatter plot where I m using another array whose values are presented as colormap. That array effectively has values from 1e3 to 1e6 (usually). Code: h3 = ax12.scatter(x[j], y[j], c=temp[j], marker='.', s=10.0, cmap='hot', edgecolors='none') That h3 is passed to plt.colorbar and values are in temp[] array. – Nemanja Martinovic May 01 '17 at 11:56

2 Answers2

5

It's in general not possible to change the position of the offsetText label. This would still be an open issue.

A solution can therefor be to overwrite the yaxis' _update_offset_text_position method to position the offsetText on the bottom of the yaxis.

import matplotlib.pyplot as plt
import types

def bottom_offset(self, bboxes, bboxes2):
    bottom = self.axes.bbox.ymin
    self.offsetText.set(va="top", ha="left")
    self.offsetText.set_position(
            (0, bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72.0))

fig, ax = plt.subplots()
im = ax.imshow([[1e5,2e5],[0.1e5,1e5]])
cb = plt.colorbar(im)
cb.formatter.set_scientific(True)
cb.formatter.set_powerlimits((0,0))

def register_bottom_offset(axis, func):
    axis._update_offset_text_position = types.MethodType(func, axis)
register_bottom_offset(cb.ax.yaxis, bottom_offset)

cb.update_ticks()

plt.show()

enter image description here

If the colorbar is positioned on the left side of the plot the following might look better:

self.offsetText.set(va="top", ha="right")
self.offsetText.set_position(
            (1, bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72.0))
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
4

Hmmm... Apparently, it's not possible to move colorbar's scientific base multiplier up or down, just slightly left or right.

Workaround would be to hide it and just add (same) custom text that would be positioned at the bottom (in my case):

    cb.ax.yaxis.get_offset_text().set_visible(False)
    cb.ax.text(0.5, -0.1, '1e4', va='bottom', ha='center', size=6)

If someone has more elegant solution, I would be happy to see it!