簡體   English   中英

出現錯誤的值…使用python matplotlib.ticker(ax.xaxis.set_major_locator)

[英]Wrong values appears… using python matplotlib.ticker (ax.xaxis.set_major_locator)

我很難通過使用matplotlib.ticker方法來獲取正確的x-ticks值。 這是描述我的問題的簡單工作示例。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

## Sample code
np.arange(0, 15, 5)
plt.figure(figsize = [6,4])

x=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
y=np.array([15,16,17,18,19,20,40,50,60,70,80,90,100,110,120])
ax = sns.pointplot(x,y, color='k', markers=["."], scale = 2)  
ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator([1,5,8]))

結果:x-點位於正確的位置(1,5,8),但我想要的那些位置的值是1,5,8(對應的x值),而不是(1,2,3)

我已經嘗試過https://matplotlib.org/examples/ticks_and_spines/tick-locators.html中解釋的所有定位符,但是都顯示了1,2,3個x-ticks值... :(

wrongtickvalue

我的實際問題(遇到相同問題的麻煩:x-ticks應該類似於64、273.5、1152.5,而不是前三個數字)

...
print(intervals}
>> [64, 74, 86.5, 10.1, 116.0, 132.0, 152.0, 175.5, 204.0, 236.0, 273.5, 319.0, 371.0, 434.0, 509.0, 595.5, 701.0, 861.0, 1152.5]

ax.xaxis.set_major_locator(matplotlib.ticker.LinearLocator(3)
plt.show()

wrong_tick_value2

您已經成功設置了定位器。 s的位置確實在位置1,5,8。

您缺少的是格式化程序。 您想在這些位置顯示什么值?
您可以使用FixedFormatter ,指定要顯示的標簽,

ax.xaxis.set_major_formatter(matplotlib.ticker.FixedFormatter([1,5,8]))

您同樣可以使用ScalarFormatter ,它會根據它們的位置自動選擇刻度標簽。

ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())

完整的代碼:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns

## Sample code
np.arange(0, 15, 5)
plt.figure(figsize = [6,4])

x=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
y=np.array([15,16,17,18,19,20,40,50,60,70,80,90,100,110,120])
ax = sns.pointplot(x,y, color='k', markers=["."], scale = 2)  
ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator([1,5,8]))
ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
# or use
#ax.xaxis.set_major_formatter(matplotlib.ticker.FixedFormatter([1,5,8]))

plt.show()

在此處輸入圖片說明


在這里使用海洋點狀圖可能不是最佳選擇。 常見的matplotlib圖更有意義。 在這種情況下,僅設置定位器就足夠了,因為格式化程序已經自動設置為ScalarFormatter。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns

## Sample code
np.arange(0, 15, 5)
plt.figure(figsize = [6,4])

x=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
y=np.array([15,16,17,18,19,20,40,50,60,70,80,90,100,110,120])
plt.plot(x,y, marker="o") 
plt.gca().xaxis.set_major_locator(matplotlib.ticker.FixedLocator([1,5,8]))

plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM