[英]On matplotlib logarithmic axes labels
尊敬的matplotlib社區,
關於對數軸標簽,我有一個非常快速的問題,我敢肯定你們中的一員可以在戴上帽子時回答。
本質上我在matplotlib中有一個對數軸,標簽為10 ^ -2、10 ^ -1、10 ^ 0、10 ^ 1、10 ^ 2等
但是,我想要0.01、0.1、1、10、100。
誰能在這方面指導我。 我嘗試了一些選擇,例如:
ax.set_xticks([0.01,0.1,1,10,100])
ax.set_xlabels([0.01,0.1,1,10,100])
任何專業提示將不勝感激!
首先,應代替set_xlabels
調用set_xticklabels
作為實際的刻度標簽。 也就是說,至少在我當前的環境(python 2.7,matplotlib 1.4.3,OS X 10.10)中,這並不總是足夠的。 在REPL(例如ipython)中逐條指令進行指令時,有時需要在調用set_xticklabels
之后更新軸。 一個快速的技巧是簡單地調用grid(True)
或grid(False)
。 例如:
x = np.logspace(-2,2, 1000)
y = np.sin(x)
l = [0.01,0.1,1,10,100]
plt.semilogx(x,y)
plt.gca().set_xticks(l)
plt.gca().set_xticklabels(l)
plt.grid(True)
經驗性注釋:使用ipython的%paste
魔術貼粘貼要點時,似乎不需要使用grid(False)
技巧(有人知道為什么嗎?)
一種不錯的方法是使用matplotlib.ticker模塊的FuncFormatter類。 結合您自己制作的自定義函數定義,這可以幫助您按所需的精確方式自定義刻度線。 此特定代碼段與matplotlib使用的對數標度很好地配合。
import numpy as np
import matplotlib.pylab as plt
x = np.linspace(-10,10)
y = np.exp(x)
plt.close('all')
fig,ax = plt.subplots(1,1)
ax.plot(x,y,'bo')
ax.set_yscale('log')
#Placed the import/function definitions here to emphasize
#the working lines of code for this particular task.
from matplotlib.ticker import FuncFormatter
def labeller(x, pos):
"""
x is the tick value, pos is the position. These args are needed by
FuncFormatter.
"""
if x < 1:
return '0.'+'0'*(abs(int(np.log10(x)))-1)+\
format(x/10**(np.floor(np.log10(x))),'.0f')
else:
return format(x,'.0f')
#FuncFormatter class instance defined from the function above
custom_formatter = FuncFormatter(labeller)
ax.yaxis.set_major_formatter(custom_formatter)
plt.show()
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.