简体   繁体   English

matplotlib 中的科学记数法颜色条

[英]Scientific notation colorbar in matplotlib

I am trying to put a colorbar to my image using matplotlib.我正在尝试使用 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?如何在颜色条的刻度中强制使用科学记数法(即 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!谢谢!

You could use colorbar 's format parameter :您可以使用colorbarformat参数

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

There is a more straightforward (but less customizable) way to get scientific notation in a ColorBar without the %.0e formatting.在没有%.0e格式的情况下,有一种更直接(但不太可定制)的方法可以在ColorBar中获取科学记数法。

Create your ColorBar :创建您的ColorBar

cbar = plt.colorbar()

And call the formatter:并调用格式化程序:

cbar.formatter.set_powerlimits((0, 0))

This will make the ColorBar use scientific notation.这将使ColorBar使用科学记数法。 See the example figure below to see how the ColorBar will look.请参阅下面的示例图以了解ColorBar的外观。

在此处输入图像描述

The documentation for this function can be found here .这个函数的文档可以在这里找到。

It seems that cbar.formatter.set_powerlimits((0,0)) alone in Joseph's answer does not render math format like $10^3$ yet.似乎约瑟夫的答案中单独的cbar.formatter.set_powerlimits((0,0))还没有呈现像 $10^3$ 这样的数学格式。

Using further cbar.formatter.set_useMathText(True) gives something like $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()

generates plot .生成情节

See the document of set_useMathText() here .请参阅此处set_useMathText()文档。

PS: Maybe this suits best for a comment. PS:也许这最适合发表评论。 But I do not have enough reputations.但我没有足够的声誉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM