Python matplotlib 中的科学记数法颜色条
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25983218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scientific notation colorbar in matplotlib
提问by Alejandro
I am trying to put a colorbar to my image using matplotlib. The issue comes when I try to force the ticklabels to be written in scientific notation. How can I force the scientific notation (ie, 1x10^0, 2x10^0, ..., 1x10^2, and so on) in the ticks of the color bar?
我正在尝试使用 matplotlib 为我的图像添加颜色条。当我试图强制用科学记数法书写刻度标签时,问题就出现了。如何在颜色条的刻度中强制使用科学记数法(即 1x10^0、2x10^0、...、1x10^2 等)?
Example, let's create and plot and image with its color bar:
例如,让我们用它的颜色条创建和绘制图像:
import matplotlib as plot
import numpy as np
img = np.random.randn(300,300)
myplot = plt.imshow(img)
plt.colorbar(myplot)
plt.show()
When I do this, I get the following image:
当我这样做时,我得到以下图像:


However, I would like to see the ticklabels in scientific notation... Is there any one line command to do this? Otherwise, is there any hint out there? Thanks!
但是,我想看到科学记数法中的刻度标签......是否有任何一行命令可以做到这一点?否则,那里有任何提示吗?谢谢!
采纳答案by unutbu
You could use colorbar's formatparameter:
您可以使用colorbar'sformat参数:
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()


回答by Falko
You can specify the format of the colorbar ticks as follows:
您可以按如下方式指定颜色条刻度的格式:
pl.colorbar(myplot, format='%.0e')

