Scientific notation colorbar in matplotlib

Question:

I am trying to put a colorbar to my image using matplotlib. The issue comes when I try to force the ticklabels to be written in scientific notation. How can I force the scientific notation (ie, 1×10^0, 2×10^0, …, 1×10^2, and so on) in the ticks of the color bar?

Example, let’s create and plot and image with its color bar:

import matplotlib as plot
import numpy as np

img = np.random.randn(300,300)
myplot = plt.imshow(img)
plt.colorbar(myplot)
plt.show()

When I do this, I get the following image:

image created with the previous code

However, I would like to see the ticklabels in scientific notation… Is there any one line command to do this? Otherwise, is there any hint out there? Thanks!

Asked By: Alejandro

||

Answers:

You could use colorbar‘s format parameter:

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

img = np.random.randn(300,300)
myplot = plt.imshow(img)

def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} times 10^{{{}}}$'.format(a, b)

plt.colorbar(myplot, format=ticker.FuncFormatter(fmt))
plt.show()

enter image description here

Answered By: unutbu

You can specify the format of the colorbar ticks as follows:

pl.colorbar(myplot, format='%.0e')
Answered By: Falko

There is a more straightforward (but less customizable) way to get scientific notation in a ColorBar without the %.0e formatting.

Create your ColorBar:

cbar = plt.colorbar()

And call the formatter:

cbar.formatter.set_powerlimits((0, 0))

This will make the ColorBar use scientific notation. See the example figure below to see how the ColorBar will look.

enter image description here

The documentation for this function can be found here.

Answered By: Joseph Farah

It seems that cbar.formatter.set_powerlimits((0,0)) alone in Joseph’s answer does not render math format like $10^3$ yet.

Using further cbar.formatter.set_useMathText(True) gives something like $10^3$.

import matplotlib.pyplot as plt
import numpy as np

img = np.random.randn(300,300)*10**5
myplot = plt.imshow(img)
cbar = plt.colorbar(myplot)
cbar.formatter.set_powerlimits((0, 0))

# to get 10^3 instead of 1e3
cbar.formatter.set_useMathText(True)

plt.show()

generates
plot.

See the document of set_useMathText() here.

PS: Maybe this suits best for a comment. But I do not have enough reputations.

Answered By: Guang-Le Du