Reputation: 6651
With the matplotlib colorbar, often the numbers will be printed in scientific notation, with only the mantissas showing on the side of the bar, and with a single exponent sitting at the top of the bar. I get this format often, even when I don't want it. Now, I really need it because I am plotting small numbers with like six zeros in decimal notation, and suddenly matplotlib decides it wants to print its numbers in decimal format instead of its scientific format. Is there any way to force it to use scientific notation with the single exponent at the top of the bar?
Upvotes: 3
Views: 2379
Reputation: 6651
Found it.
The colorbar has an optional format
argument. You can specify straightforward scientific notation or decimal formats with simple text arguments. You can also supply a ScalarFormatter
object as an argument. The ScalarFormatter object has a function set_powerlimits(min,max)
. If it calls that function, any number less than 10^min or greater than 10^max will be expressed in scientific notation. If the entire range of your colorbar values is less than 10^min or greater than 10^max, your colorbar will display the results as requested in the OP: scientific notation with only mantissas on the sides of the bar and a single exponent at the top. For my case, where the colorbar values were all on the order of 10^-6, I did:
import matplotlib.ticker # here's where the formatter is
cbformat = matplotlib.ticker.ScalarFormatter() # create the formatter
cbformat.set_powerlimits((-2,2)) # set the limits for sci. not.
# do whatever plotting you have to do
fig = plt.figure()
ax1 = # create some sort of axis on fig
plot1 = ax1.... # do your plotting here ... plot, contour, contourf, whatever
# now add colorbar with your created formatter as an argument
fig.colorbar(plot1, ax=ax1, format=cbformat)
Upvotes: 2