2012-03-11 8 views
5

私はx軸の時間に対してプロットを作成する方法を探していましたが、それはかなり奇妙なものでした。私が本当に理解していないことをやっていることは間違いないでしょう。Python/matplotlibでxaxis_date()を手動で設定する

簡単に言えば、以下は私のプログラムの簡略版です。これを.pyファイルに入れてインタプリタ(ipython)から実行すると、x軸に年だけの "2012"という数字が複数回繰り返されます(like this)。

しかし、xticksを手動で設定する行(40)、つまり 'plt.xticks(tk)'をコメントアウトしてから、スクリプトを実行した直後にインタプリタで正確なコマンドを実行すると、図はlike thisのように見えます。

同様に、スクリプトのsavefigコマンドの後に行を移動するだけで、それはファイルの最後に置くことになります。もちろん、どちらの場合でも、スクリーンに描画された図形だけが、保存されたファイルではなく、目的の軸を持つことになります。 x軸を先に設定できないのはなぜですか?

事前に感謝の意を表します。

import matplotlib.pyplot as plt 
import datetime 

# define arrays for x, y and errors 
x=[16.7,16.8,17.1,17.4] 
y=[15,17,14,16] 
e=[0.8,1.2,1.1,0.9] 

xtn=[] 

# convert x to datetime format 
for t in x: 
    hours=int(t) 
    mins=int((t-int(t))*60) 
    secs=int(((t-hours)*60-mins)*60) 
    dt=datetime.datetime(2012,01,01,hours,mins,secs) 
    xtn.append(date2num(dt)) 

# set up plot 
fig=plt.figure() 
ax=fig.add_subplot(1,1,1) 

# plot 
ax.errorbar(xtn,y,yerr=e,fmt='+',elinewidth=2,capsize=0,color='k',ecolor='k') 

# set x axis range 
ax.xaxis_date() 
t0=date2num(datetime.datetime(2012,01,01,16,35)) # x axis startpoint 
t1=date2num(datetime.datetime(2012,01,01,17,35)) # x axis endpoint 
plt.xlim(t0,t1) 

# manually set xtick values 
tk=[] 
tk.append(date2num(datetime.datetime(2012,01,01,16,40))) 
tk.append(date2num(datetime.datetime(2012,01,01,16,50))) 
tk.append(date2num(datetime.datetime(2012,01,01,17,00))) 
tk.append(date2num(datetime.datetime(2012,01,01,17,10))) 
tk.append(date2num(datetime.datetime(2012,01,01,17,20))) 
tk.append(date2num(datetime.datetime(2012,01,01,17,30))) 
plt.xticks(tk) 

plt.show() 

# save to file 
plt.savefig('savefile.png') 

答えて

5

xaxis_date()への呼び出しは必要ありません。 matplotlibが扱う方法を知っている形式でx軸データを提供しているからです。私はまた、あなたのsecs式に若干問題があると思います。

我々はmatplotlibの内蔵のフォーマッタとロケータを利用することができます:

  1. 一定の間隔(分、時間、日、など)への主要なxticksを設定し使用して表示をカスタマイズstrftime書式指定文字列

フォーマッタが指定されていない場合、デフォルトでは年が表示されます。それはあなたが見ていたものです。

これを試してみてください:

import datetime as dt 
import matplotlib.pyplot as plt 
from matplotlib.dates import DateFormatter, MinuteLocator 

x = [16.7,16.8,17.1,17.4] 
y = [15,17,14,16] 
e = [0.8,1.2,1.1,0.9] 
xtn = [] 
for t in x: 
    h = int(t) 
    m = int((t-int(t))*60) 
    xtn.append(dt.datetime.combine(dt.date(2012,1,1), dt.time(h,m))) 

def larger_alim(alim): 
    ''' simple utility function to expand axis limits a bit ''' 
    amin,amax = alim 
    arng = amax-amin 
    nmin = amin - 0.1 * arng 
    nmax = amax + 0.1 * arng 
    return nmin,nmax 

plt.errorbar(xtn,y,yerr=e,fmt='+',elinewidth=2,capsize=0,color='k',ecolor='k') 
plt.gca().xaxis.set_major_locator(MinuteLocator(byminute=range(0,60,10))) 
plt.gca().xaxis.set_major_formatter(DateFormatter('%H:%M:%S')) 
plt.gca().set_xlim(larger_alim(plt.gca().get_xlim())) 
plt.show() 

結果:

enter image description here

FWIW larger_alimは、もともとこの他の質問のために書かれたユーティリティ関数:Is there a way to tell matplotlib to loosen the zoom on the plotted data?

関連する問題