2017-07-31 140 views
2

我正在一個數字,其中X軸應該是對數間隔,但我想手動設置刻度標籤,我希望刻度標籤出現在普通'%.2f'表示法,而不是指數表示法。基於Matplotlib - logarithmic scale, but require non-logarithmic labels以下解決方案建議使用ScalarFormatter,但不與matplotlib 2.0工作:matplotlib數字與對數軸,但沒有科學/指數符號

x = np.logspace(2, 3, 100) 
y = x 

fig, ax = plt.subplots(1, 1) 
xscale = ax.set_xscale('log') 
ax.set_xticks((100, 200, 300, 500)) 
xlim = ax.set_xlim(100, 1000) 

from matplotlib.ticker import ScalarFormatter 
ax.get_xaxis().set_major_formatter(ScalarFormatter()) 

__=ax.plot(x, y) 

enter image description here

回答

2

確實有可能使用ScalarFormatter。然後,您需要確保沒有未成年人ticklabels中顯示爲這個問題看到:Matplotlib: setting x-limits also forces tick labels?

在你的情況,那麼該代碼看起來像:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.logspace(2, 3, 100) 
y = x 

fig, ax = plt.subplots(1, 1) 
xscale = ax.set_xscale('log') 
ax.set_xticks((100, 200, 300, 500)) 
xlim = ax.set_xlim(100, 1000) 

import matplotlib.ticker 

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) 
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter()) 

__=ax.plot(x, y) 

plt.show() 

enter image description here

2

因爲你是被硬編碼軸的最小值和最大值,它看起來像你試圖一次性創建圖表,而不是以編程方式爲更一般的數據創建圖表。在這種情況下,特別是因爲您已經獲得了對x-xais的引用,所以可以將刻度標籤字符串放在列表中,並使用軸方法set_ticklabels。一般來說,請參閱API for axis and tick objects

+0

感謝貝內特,雖然我我認爲我必須錯誤地實施你的建議。以下不會產生所需的結果:ax.get_xaxis()。set_ticklabels(('100','200','300','500'))。 API /文檔表明你是正確的,所以不要澄清我做錯了什麼。 – aph

+0

您需要一個長度等於滴答數量的列表:'set_ticklabels([「100」,「200」,「」,「」,「」,「」,「」,「」,「」,「1000」 ])'。 '*'在Python中的列表上工作,所以我會使用'set_ticklabels([「100」,「200」] + [「」] * 7 + [「1000」])''。 –

+0

另外,如果你設置了'set_xlim',我認爲''set_ticks'會重新設置,覆蓋之前調用'set_ticks'的效果,這可以在你的圖形中看到。這就是爲什麼蜱列表的長度不是4. –

相關問題