【问题标题】:Python Plot: How to denote ticks on the axes as powers?Python Plot:如何将轴上的刻度表示为幂?
【发布时间】:2016-04-07 15:01:39
【问题描述】:

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

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

【问题讨论】:

标签: python python-2.7 matplotlib plot


【解决方案1】:

您可以使用matplotlib.ticker 模块,并将ax.xaxis.set_major_formatter 设置为FuncFormatter

例如:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多