Python 如何以分数标记x轴?
我想使用分数标记轴,以准确显示数据点的位置。例如,在下面的代码中,我想标记x轴“1/13,2/13,3/13…” 如何做到这一点Python 如何以分数标记x轴?,python,numpy,matplotlib,fractions,Python,Numpy,Matplotlib,Fractions,我想使用分数标记轴,以准确显示数据点的位置。例如,在下面的代码中,我想标记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() 两件事 您需要设置记号标签 请参阅此处以获取详细答案: 您需要将标
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()
两件事
您需要设置记号标签
请参阅此处以获取详细答案:
您需要将标签格式化为分数。
在这里,您可以为每个标签生成一个字符串:
类似这样的东西(未经测试)
您可以使用模块完成此操作。我们需要使用
ax.xaxis.set_major_locator
及
我们将使用a将记号放置在给定的分数上(即步骤
的每一个倍数),然后使用a将记号标签呈现为分数
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()
ax.xaxis.set_major_formatter
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()