Python绘图:如何将轴上的记号表示为幂?

2024-05-13 06:09:38 发布

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

我在python中使用matplot库进行绘图。这些坐标轴上的数字也很大。我试着把它们作为一种异能来呈现(例如,我想要10^8而不是勾选100000000)。我使用了命令:ax.ticklabel_format(style='sci', axis='x', scilimits=(0,4))但是这只创建了这样的东西

enter image description here

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


Tags: 命令format绘图style数字解决方案axsci
2条回答

可能有更好的解决方案,但是如果知道每个xtick的值,也可以手动命名它们。 下面是一个例子: http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

您可以使用^{}模块,并将ax.xaxis.set_major_formatter设置为^{}。在

例如:

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

enter image description here

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

相关问题 更多 >