Python Plot:如何将轴上的刻度表示为幂?

Ziv*_*iva 2 python plot matplotlib python-2.7

我在python使用matplot图书馆的情节上工作。我必须生成的数字非常大,所以轴上的刻度也是一个很大的数字,占用大量空间。我试图将它们呈现为一种权力(例如,我想要 10^8,而不是打勾 100000000)。我使用命令:ax.ticklabel_format(style='sci', axis='x', scilimits=(0,4))但是这只创建了这样的东西

在此处输入图片说明

是否有其他解决方案可以将绘图的刻度设置为:1 x 10^4、2 x 10^4 等,或者在标签刻度的末尾将值 1e4 写为 10^4?

tmd*_*son 6

您可以使用该matplotlib.ticker模块,并将其设置ax.xaxis.set_major_formatterFuncFormatter.

例如:

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

plt.rcParams['text.usetex'] = True

fig,ax = plt.subplots(1)

x = y = np.arange(0,1.1e4,1e3)
ax.plot(x,y)

def myticks(x,pos):

    if x == 0: return "$0$"

    exponent = int(np.log10(x))
    coeff = x/10**exponent

    return r"${:2.0f} \times 10^{{ {:2d} }}$".format(coeff,exponent)

ax.xaxis.set_major_formatter(ticker.FuncFormatter(myticks))

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

请注意,这使用LaTeX格式 ( text.usetex = True) 在刻度标签中呈现指数。还要注意区分LaTeX大括号和 python 格式字符串大括号所需的双大括号。