python - 如何用分数标记 x 轴?

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

最佳答案

您可以使用 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()

enter image description here

关于python - 如何用分数标记 x 轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780678/

相关文章:

python - 找不到语言 json 的内核 - 原子上的氢

python - 从 3D numpy 数组中选择多个补丁

python - 控制对数刻度的刻度间距

python - 提取 pandas 数据框中一组行之后的行窗口

python - 使用 matplotlib pcolor 时出现多余的白色

matplotlib - savefig 错误

python绘制一系列值的水平线

python - 为什么 P4Python 无法识别 P4CONFIG 设置?

python - 将 12 小时格式时间字符串(含 am/pm)转换为 24 小时格式的 UTC

python - 使用 Python 的 cx_Freeze 安装程序添加开始菜单快捷方式