【问题标题】:matplotlib colorbar: need to force scientific notation with exponent at top of barmatplotlib colorbar:需要在条形顶部使用指数强制科学记数法
【发布时间】:2019-08-13 20:45:03
【问题描述】:
使用 matplotlib 颜色栏,通常会以科学计数法打印数字,只有尾数显示在栏的一侧,并且在栏的顶部有一个指数。我经常得到这种格式,即使我不想要它。现在,我真的需要它,因为我正在用十进制表示法绘制像六个零这样的小数字,突然 matplotlib 决定它想要以十进制格式而不是科学格式打印它的数字。有什么办法可以强制它使用科学记数法和条形顶部的单个指数?
【问题讨论】:
标签:
matplotlib
colorbar
scientific-notation
【解决方案1】:
找到了。
颜色条有一个可选的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)