如何在颜色条顶部强制使用指数的科学计数法

问题描述 投票:0回答:1

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

python matplotlib colorbar scientific-notation
1个回答
2
投票

找到了。

颜色栏有一个可选的

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)
© www.soinside.com 2019 - 2024. All rights reserved.