我正在尝试使用 matplotlib 将颜色条添加到我的图像中。当我尝试强制以科学记数法书写刻度标签时,问题就出现了。如何在颜色条的刻度中强制使用科学计数法(即 1x10^0、2x10^0、...、1x10^2 等)?
例如,让我们使用其颜色条创建并绘制图像:
import matplotlib as plot
import numpy as np
img = np.random.randn(300,300)
myplot = plt.imshow(img)
plt.colorbar(myplot)
plt.show()
当我这样做时,我得到以下图像:
但是,我想以科学计数法查看刻度标签...是否有任何一行命令可以执行此操作?不然的话,还有什么提示吗?谢谢!
colorbar
的format
参数:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker
img = np.random.randn(300,300)
myplot = plt.imshow(img)
def fmt(x, pos):
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
return r'${} \times 10^{{{}}}$'.format(a, b)
plt.colorbar(myplot, format=ticker.FuncFormatter(fmt))
plt.show()
您可以指定颜色条刻度的格式,如下所示:
pl.colorbar(myplot, format='%.0e')
有一种更直接(但可定制性较差)的方法可以在
ColorBar
中获取科学记数法,而无需 %.0e
格式。
创建您的
ColorBar
:
cbar = plt.colorbar()
并调用格式化程序:
cbar.formatter.set_powerlimits((0, 0))
这将使
ColorBar
使用科学记数法。请参阅下面的示例图,了解 ColorBar
的外观。
可以在此处找到此功能的文档。
约瑟夫的答案中的
cbar.formatter.set_powerlimits((0,0))
似乎还没有呈现像$10^3$这样的数学格式。
添加
cbar.formatter.set_useMathText(True)
会得到类似 $10^3$ 的东西。
import matplotlib.pyplot as plt
import numpy as np
img = np.random.randn(300,300)*10**5
myplot = plt.imshow(img)
cbar = plt.colorbar(myplot)
cbar.formatter.set_powerlimits((0, 0))
# to get 10^3 instead of 1e3
cbar.formatter.set_useMathText(True)
plt.show()
参见
set_useMathText()
这里的文档。