Python 添加+;matplotlib轴中的指数符号

Python 添加+;matplotlib轴中的指数符号,python,python-2.7,matplotlib,Python,Python 2.7,Matplotlib,我有一个日志图,其范围从10^-3到10^+3。我想要数值≥10^0在指数中有一个类似于值的符号+我希望这就是你的意思: def fmt(y, pos): a, b = '{:.2e}'.format(y).split('e') b = int(b) if b >= 0: format_example = r'$10^{+{}}$'.format(b) else: format_example = r'$10^{{}}$'.forma

我有一个日志图,其范围从
10^-3
10^+3
。我想要数值
≥10^0
在指数中有一个类似于值的符号
+
我希望这就是你的意思:

def fmt(y, pos):
    a, b = '{:.2e}'.format(y).split('e')
    b = int(b)
    if b >= 0:
      format_example = r'$10^{+{}}$'.format(b)
    else:
      format_example = r'$10^{{}}$'.format(b)
    return
然后使用
FuncFormatter
,例如,对于颜色条:
plt.colorbar(绘图的名称,勾号=带勾号位置的列表,格式=勾号.FuncFormatter(fmt))
。我认为您必须导入
导入matplotlib.ticker作为ticker


关于

您可以使用
matplotlib.ticker
模块中的
FuncFormatter
执行此操作。您需要一个关于刻度值是否大于或小于1的条件。因此,如果
log10(勾号值)
>0
,则在标签字符串中添加
+
符号,如果不是,则它将自动获得其减号

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

# sample data
x = y = np.logspace(-3,3)

# create a figure
fig,ax = plt.subplots(1)

# plot sample data
ax.loglog(x,y)

# this is the function the FuncFormatter will use
def mylogfmt(x,pos):
    logx = np.log10(x) # to get the exponent
    if logx < 0:
        # negative sign is added automatically  
        return u"$10^{{{:.0f}}}$".format(logx)
    else:
        # we need to explicitly add the positive sign
        return u"$10^{{+{:.0f}}}$".format(logx)

# Define the formatter
formatter = ticker.FuncFormatter(mylogfmt)

# Set the major_formatter on x and/or y axes here
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)

plt.show()

双大括号
{{
}
被传递到
LaTeX
,以表示其中的所有内容都应作为指数提升。我们需要双大括号,因为python使用单大括号来包含格式字符串,在本例中为
{.0f}
。有关格式规范的更多说明,请参见,但TL;您的情况是,我们正在格式化精度为0位小数的浮点(即,基本上打印为整数);在这种情况下,指数是一个浮点数,因为
np.log10
返回一个浮点数。(也可以将
np.log10
的输出转换为int,然后将字符串格式化为int,这取决于您的偏好).

你的意思是你想像那样格式化x轴和y轴上记号的注释吗?@tokamak-目前实际上只对y轴感兴趣,但最好单独设置两个轴查看生成记号的代码,看起来没有明显的方法自己更改它。我想一个非最佳的方法是只创建一个修改版的823行。@SimonGibbons,总是有办法改变的,你只需要知道去哪里看就行了!在本例中,OP已经提到了
FuncFormatter
,这正是我们需要的工具。好的,我将使用这个。。。你能解释一下
{{:.0f}}
的格式吗我猜多余的括号是用来转义的,但是
:.0f
到底做什么呢?
"$10^{{+{:.0f}}}$".format(logx)