我想用分数标记轴以准确显示数据点的位置。例如,在下面的代码中我想标记 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()
最佳答案
您可以使用 matplotlib.ticker
执行此操作模块。我们需要为 xaxis
刻度设置格式器和定位器,使用
ax.xaxis.set_major_locator
和
ax.xaxis.set_major_formatter
我们将使用 MultipleLocator
将刻度放在给定的分数上(即 step
的每个倍数),然后是 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()
关于python - 如何用分数标记 x 轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780678/