2011-06-14 47 views
0

1 Xticklabels不工作Matplotlib Xticklabels不工作

我使用Matplotlib生成一些測量直方圖:

import matplotlib 
matplotlib.use('Agg') 
import matplotlib.pyplot as pyplot 
... 
fig = pyplot.figure() 
ax = fig.add_subplot(1,1,1,) 
n, bins, patches = ax.hist(measurements, bins=50, range=(graph_minimum, graph_maximum), histtype='bar') 

ax.set_xticklabels([n], rotation='vertical') 


for patch in patches: 
    patch.set_facecolor('r') 

pyplot.title='Foobar' 
#pyplot.grid(True) 
pyplot.xlabel('X-Axis') 
pyplot.ylabel('Y-Axis') 
pyplot.savefig(output_filename) 

產生的PNG看起來不錯,除了兩個問題:

  1. 標題('垃圾郵件和火腿')從PNG中丟失。 x和y軸標籤都存在(雖然我沒有爲以下示例打開它們)。
  2. x-tick-lables看起來完全被破壞了 - 而不是沿着所有酒吧底部的底部顯示,它被渲染爲圖的左下方的一行數字,該行被切斷。它似乎也禁用了我的Y軸標籤。

Histogram with broken xticklabels

2.單位和SI前綴

注:不Matplotlib具體。

直方圖具有沿着x軸的時間測量。這些範圍從微秒範圍到毫秒和秒範圍。目前,該圖正在將x軸標籤以標準符號表示爲秒。

Time in seconds along x-axis

我想友好的格式,我寧願時間是以毫秒爲單位/微秒值給出,與單位顯示。所以這意味着我想用友好的格式來表示一個時間值,並具有SI前綴的意識。

事實上,它可能是頗爲相似的示例程序在這裏:

http://diveintopython3.org/your-first-python-program.html

我也注意到有這麼做處理單位一些Python庫:

  1. http://juanreyero.com/open/magnitude/index.html
  2. http://home.scarlet.be/be052320/Unum.html
  3. http://pypi.python.org/pypi/units/

但是,從我讀過的東西看來,它似乎不像以上任何一種處理SI前綴,或者做這種友好的格式。任何建議/選擇?

回答

3

1.1:標題('垃圾郵件和火腿')從PNG中丟失。

你寫

pyplot.title='Foobar' 

你想

pyplot.title("Spam and Ham") 

pyplot.title = 'Foobar的' 簡單地用字符串替換標題功能。

1.2:在X-蜱標貼似乎完全打破

ISTM ax.set_xticklabels([n], rotation='vertical')可能不是你想要做的,因爲我不認爲ñ什麼是什麼,你認爲它是。對於測量[1,2,3,4],我們得到:

>>> n, bins, patches = ax.hist([1,2,3,4]) 
>>> n 
array([1, 0, 0, 1, 0, 0, 1, 0, 0, 1]) 
>>> bins 
array([ 1. , 1.3, 1.6, 1.9, 2.2, 2.5, 2.8, 3.1, 3.4, 3.7, 4. ]) 
>>> patches 
<a list of 10 Patch objects> 

n是一個數組,其中包含計數在箱中,而不是箱位置;它是y軸,而不是x。而且,它已經是一個列表,所以使用[n]不應該是必須的。我不確定你想要做什麼,但是你可以從箱子中製作字符串標籤(除非你想要很多數字!),或者,如果你只希望xtick標籤是垂直的,你可以使用

for label in ax.get_xticklabels(): 
    label.set_rotation('vertical') 

恐怕我對單元庫一無所知。

+0

DSM:感謝您的幫助。是的,標題問題解決了 - 愚蠢的,應該閱讀文檔=)。我設法將n數組「n」投入列表中,並且它有效,但不是真的。但你是對的,這不是我想要的。無論如何,我已經給你這個答案=)。我將更專門針對xtick問題重新提出問題 - http://stackoverflow.com/questions/6352740/matplotlib-label-each-bin – victorhooi 2011-06-15 03:34:19

0

要將SI前綴添加到要使用的軸標籤QuantiPhy。事實上,在它的文檔中有一個例子說明如何做到這一點:MatPlotLib Example

我想你會添加一些像這樣的代碼:

from matplotlib.ticker import FuncFormatter 
from quantiphy import Quantity 

time_fmtr = FuncFormatter(lambda v, p: Quantity(v, 's').render(prec=2)) 
ax.xaxis.set_major_formatter(time_fmtr)