matplotlib colorbar: need to force scientific notation with exponent at top of bar

╄→гoц情女王★ 提交于 2019-12-02 10:59:36

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/55306803/matplotlib-colorbar-need-to-force-scientific-notation-with-exponent-at-top-of-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!