matplotlib轴上的精度不同

Mat*_*u22 4 python graphics matplotlib

我的老师说,在图表中我必须标记轴0, 0.25, 0.5而不是0.00,0.25,0.50,....我知道如何将它标记为0.00,0.25,0.50 (plt.yticks(np.arange(-1.5,1.5,.25))),但是,我不知道如何以不同的精度绘制ticklabels.

我试过这样做

plt.yticks(np.arange(-2,2,1))
plt.yticks(np.arange(-2.25,2.25,1))
plt.yticks(np.arange(-1.5,2.5,1))
Run Code Online (Sandbox Code Playgroud)

无济于事.

joh*_*mik 9

这已经得到了回答,例如Matplotlib:为tick标签指定浮点数的格式.但实际上您希望使用的格式与引用的问题中使用的格式不同.

因此,此代码为您提供y轴上的所需精度

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

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
ax.yaxis.set_ticks(np.arange(-2, 2, 0.25))

x = np.arange(-1, 1, 0.1)
plt.plot(x, x**2)
plt.show()
Run Code Online (Sandbox Code Playgroud)

您可以在传递给FormatStrFormatter的String中定义所需的精度.在上面的例子中,它是"%g",代表一般格式.此格式删除无关紧要的尾随零.您还可以传递其他格式,例如"%.1f",这将是一个小数位的精度,而"%.3f"将是三位小数的精度.这些格式在这里详细解释.


Imp*_*est 5

为了将刻度的位置设置为 0.25 的倍数,您可以使用matplotlib.ticker.MultipleLocator(0.25). 然后,您可以使用FuncFormatter带有从数字右侧去除零的函数来格式化刻度标签。

import matplotlib.pyplot as plt
import matplotlib.ticker

plt.plot([-1.5,0,1.5],[1,3,2])
ax=plt.gca()

f = lambda x,pos: str(x).rstrip('0').rstrip('.')
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(f))
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明