如何用分数标记 x 轴?

How to label the x axis in fraction numbers?

我想用分数标记轴以准确显示数据点的位置。例如,在下面的代码中我想标记 x 轴 '1 /13,2/13,3/13...'

如何实现?

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

step=1./13.
x=np.arange(0,14)*step
y=np.sin(2*np.pi*x)
plt.plot(x,y,'r*')
plt.show()

两件事。

您需要设置刻度标签。

请参阅此处以获得详细答案:

您需要将标签格式化为分数。 在这里你可以为每个标签生成一个字符串: 像这样的(未经测试)

labels = []
n = 1.0
d=13.0
for i in range(0,14):
    labels.append(  str(n) + "/" + str(d) )
step = n/d

您可以使用 matplotlib.ticker 模块来完成此操作。我们需要使用

xaxis 刻度设置格式器和定位器
ax.xaxis.set_major_locator

ax.xaxis.set_major_formatter

我们将使用 MultipleLocator to place the ticks on the given fractions (i.e. every multiple of step), then a FuncFormatter 将刻度标签呈现为分数。

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

step=1./13.
x=np.arange(0,14)*step
y=np.sin(2*np.pi*x)

fig,ax = plt.subplots()

ax.plot(x,y,'r*')

def fractions(x,pos):
    if np.isclose((x/step)%(1./step),0.):
        # x is an integer, so just return that
        return '{:.0f}'.format(x)
    else:
        # this returns a latex formatted fraction
        return '$\frac{{{:2.0f}}}{{{:2.0f}}}$'.format(x/step,1./step)
        # if you don't want to use latex, you could use this commented
        # line, which formats the fraction as "1/13"
        ### return '{:2.0f}/{:2.0f}'.format(x/step,1./step)

ax.xaxis.set_major_locator(ticker.MultipleLocator(step))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(fractions))

plt.show()