2017-05-25 86 views
1

有人可以給我一個如何使用以下tickFormatters的例子。 docs對我沒有任何意義。Matplotlib Ticker

ticker.StrMethodFormatter() ticker.IndexFormatter()

例如我可能會認爲

x = np.array([ 316566.962, 294789.545, 490032.382, 681004.044, 753757.024, 
      385283.153, 651498.538, 937628.225, 199561.358, 601465.455]) 
y = np.array([ 208.075, 262.099, 550.066, 633.525, 612.804, 884.785, 
      862.219, 349.805, 279.964, 500.612]) 
money_formatter = tkr.StrMethodFormatter('${:,}') 

plt.scatter(x,y) 
ax = plt.gca() 
fmtr = ticker.StrMethodFormatter('${:,}') 
ax.xaxis.set_major_formatter(fmtr) 

會爲我設置刻度標記是美元符號和逗號SEP爲成千上萬的地方ALA

['$300,000', '$400,000', '$500,000', '$600,000', '$700,000', '$800,000', '$900,000'] 

而是我得到一個索引錯誤。

IndexError: tuple index out of range 

對於IndexFormatter文檔說:

從標籤列表設置字符串

真的不知道這是什麼意思,當我嘗試使用它在我的抽動消失。

+1

試着提供一個完整的例子,說明你有什麼,它產生了什麼,並解釋你想要生產什麼。 – Gabriel

回答

1

StrMethodFormatter確實通過提供可以使用format方法進行格式化的字符串。所以使用'${:,}'的方法走向了正確的方向。

但是從the documentation我們學習

用於值的字段必須標記x和用於位置字段必須標示的POS。

這意味着你需要給一個實際的標籤x到現場。此外,您可能想要指定數字格式爲g不具有小數點。

fmtr = matplotlib.ticker.StrMethodFormatter('${x:,g}') 

enter image description here

IndexFormatter是沒有多大用處的這裏。正如你發現的那樣,你需要提供一個標籤列表。這些標籤用於索引,從0開始。因此,使用此格式化程序需要將x軸從零開始,並覆蓋一些整數。

實施例:

plt.scatter(range(len(y)),y) 
fmtr = matplotlib.ticker.IndexFormatter(list("ABCDEFGHIJ")) 
ax.xaxis.set_major_formatter(fmtr) 

enter image description here

這裏,蜱被放置在(0,2,4,6,....)並從列表(A, C, E, G, I, ...)各個字母被用作標籤。

+0

好吧,我想我明白了。所以字符串'「{x:,}」'表示我們希望變量x(被mpl傳遞給格式調用)用千位分隔符格式化。現在我唯一的問題是g是什麼?這就像指定浮點型f?如果有的話,那裏還有其他的選擇嗎? – RSHAP

+0

'g'是一種通用的數字格式,如果需要,可以捨去小數點。你不需要在這裏使用它;如果你喜歡,就離開它。你可以在[官方python文檔](https://docs.python.org/3/library/string.html#format-specification-mini-language)中閱讀更多關於字符串格式的內容。 – ImportanceOfBeingErnest