matplotlib colorbar:需要在条的顶部强制使用指数的科学记数法

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

使用 matplotlib 颜色条,数字通常会以科学记数法打印,只有尾数显示在条的一侧,而单个指数位于条的顶部。我经常收到这种格式,即使我不想要它。现在,我真的需要它,因为我正在用十进制表示法绘制带有六个零的小数字,突然 matplotlib 决定要以十进制格式而不是科学格式打印其数字。有什么方法可以强制它使用科学记数法,在条形图的顶部只有一个指数?

找到了。

颜色条有一个可选的 format 参数。您可以使用简单的文本参数指定简单的科学记数法或十进制格式。您还可以提供一个 ScalarFormatter 对象作为参数。 ScalarFormatter 对象有一个函数 set_powerlimits(min,max)。如果它调用该函数,任何小于 10^min 或大于 10^max 的数字都将以科学计数法表示。如果您的颜色条值的整个范围小于 10^min 或大于 10^max,您的颜色条将按照 OP 中的要求显示结果:科学记数法,条的两侧只有尾数,条的两侧只有一个指数最佳。对于我的情况,颜色条值都在 10^-6 的数量级,我做了:

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)