matplotlib中的科学符号colorbar

2024-06-01 19:44:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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()

当我这样做时,我得到以下图像:

image created with the previous code

不过,我想看看科学记数法中的记号。。。有没有一个命令可以这么做?否则,有什么暗示吗?谢谢!


Tags: 图像importimgplotmatplotlib颜色asnp
2条回答

您可以使用^{}'s ^{} parameter

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()

enter image description here

可以按如下方式指定颜色栏刻度的格式:

pl.colorbar(myplot, format='%.0e')

相关问题 更多 >