plt.yticks 无法正常工作 - matplotlib

时间:2021-04-14 09:48:49

标签: python matplotlib

我正在使用 C# 脚本统一处理一个项目 我正在调用 Python 脚本以使用 ma​​tplotlib 在图表上绘制一些值,除了图表上的 yticks 之外,一切正常。 将要绘制的值大约在 0.5 和 5.5 之间浮动,这是供参考的图表: graph

我为设置 yticks 所做的如下:

plt.plot(x,y)
plt.yticks([0, 2, 4, 5])
plt.xlabel("frame")
plt.ylabel("distance")
plt.show()

如您所见,不是在指定位置 [0, 2, 4, 5] 有刻度,而是在 0.5 附近显示 4 个刻度。看起来无论我传递给 yticks() 的数组是什么,它都只取其中的 len() 并将准确的刻度数放在错误的位置,我猜是 y 的前 n 个值轴

Python 版本:3.8.8,Matplotlib 版本:3.4.1

非常感谢任何愿意提供帮助的人。

编辑:最小的可重现示例。 上图是使用 600 个值生成的,在下面的示例中仅使用了 50 个值,因此图形有所不同,但 ytick 问题仍然存在。

import matplotlib.pyplot as plt 

y = ['0.5356', '0.5356', '0.5615', '0.5509', '0.4958', '0.4944', '0.5056', '0.5512', '0.6314', 
     '0.7394', '0.8761', '1.0320', '1.2066', '1.3692', '1.5456', '1.7262', '1.9124', '2.0955',
     '2.2262', '2.2424', '2.2363', '2.2285', '2.1811', '2.1159', '2.0400', '1.9590', '1.8685',
     '1.7614', '1.6517', '1.5322', '1.3897', '1.2642', '1.1080', '0.9256', '0.8161', '0.6624',
     '0.5240', '0.3763', '0.2361', '0.1649', '0.2151', '0.3441', '0.5065', '0.6785', '0.8355',
     '1.0118', '1.1708', '1.3253', '1.4888', '1.6247']
x = [i for i in range(1, 51)]

# plotting
plt.plot(x,y)
plt.yticks([0, 2, 4, 5])
plt.xlabel("frame")
plt.ylabel("distance")
plt.show()

图形应该是这样的:

50frames

2 个答案:

答案 0 :(得分:0)

好吧,我是个白痴。 像往常一样,这是我做过的最愚蠢的事情。 值不是浮点数而是字符串。

答案 1 :(得分:0)

您可以像这样明确设置滴答频率:

import matplotlib.pyplot as plt 

y = ['0.5356', '0.5356', '0.5615', '0.5509', '0.4958', '0.4944', '0.5056', '0.5512', '0.6314', 
     '0.7394', '0.8761', '1.0320', '1.2066', '1.3692', '1.5456', '1.7262', '1.9124', '2.0955',
     '2.2262', '2.2424', '2.2363', '2.2285', '2.1811', '2.1159', '2.0400', '1.9590', '1.8685',
     '1.7614', '1.6517', '1.5322', '1.3897', '1.2642', '1.1080', '0.9256', '0.8161', '0.6624',
     '0.5240', '0.3763', '0.2361', '0.1649', '0.2151', '0.3441', '0.5065', '0.6785', '0.8355',
     '1.0118', '1.1708', '1.3253', '1.4888', '1.6247']
y = [float(i) for i in y]
x = [i for i in range(1, 51)]

# plotting
plt.plot(x,y)
plt.yticks(np.arange(min(y), max(y)+1, 1.0))
plt.xlabel("frame")
plt.ylabel("distance")
plt.show()

enter image description here