[英]plt.yticks not working properly - matplotlib
I'm working on a project in unity and from a C# script I'm calling a Python script to plot some values on a graph using matplotlib , everything works fine except for the yticks on the graph. 將要繪制的值是 0.5 和 5.5 之間的浮點數,這是供參考的圖表:
我為設置 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()
圖應該是這樣的:
好吧,我是個白痴。 像往常一樣,這是我做過的最愚蠢的事情。 值不是浮點數,而是字符串。
您可以像這樣顯式設置滴答頻率:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.