使用 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)