2017-02-04 26 views
9

現在、データをインポートしてmatplotlibでデータを処理する方法を学び、私は本からの正確なコードを持っていても問題があります。matplotlibのx軸を変更して、空白がないようにする方法はありますか?

enter image description here

これは、プロットは次のようになりますが、私の質問は、開始とx軸の端部との間に空白がないところ、私はそれを得ることができる方法です。ここ

コードである:matplotlibの2.xでは

import csv 

from matplotlib import pyplot as plt 
from datetime import datetime 

# Get dates and high temperatures from file. 
filename = 'sitka_weather_07-2014.csv' 
with open(filename) as f: 
    reader = csv.reader(f) 
    header_row = next(reader) 

    #for index, column_header in enumerate(header_row): 
     #print(index, column_header) 
    dates, highs = [], [] 
    for row in reader: 
     current_date = datetime.strptime(row[0], "%Y-%m-%d") 
     dates.append(current_date) 

     high = int(row[1]) 
     highs.append(high) 

# Plot data. 
fig = plt.figure(dpi=128, figsize=(10,6)) 
plt.plot(dates, highs, c='red') 


# Format plot. 
plt.title("Daily high temperatures, July 2014", fontsize=24) 
plt.xlabel('', fontsize=16) 
fig.autofmt_xdate() 
plt.ylabel("Temperature (F)", fontsize=16) 
plt.tick_params(axis='both', which='major', labelsize=16) 

plt.show() 
+0

x制限を手動で設定するために 'plt.xlim()'を使ってみましたか? http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlim – decvalts

答えて

11

データが軸棘内にうまくフィッティングであることを保証するエッジで設定された自動マージンがあります。この場合、おそらくy軸上にそのようなマージンが望ましい。デフォルトでは、軸スパンの単位で0.05に設定されています。 文脈に応じ

plt.margins(x=0) 

又は

ax.margins(x=0) 

を使用し、x軸上0にマージンを設定します。また、the documentationを参照してください。

あなたは(当然のyも同じ)、スクリプトの先頭で

plt.rcParams['axes.xmargin'] = 0 

を使用することができ、スクリプト全体に余白を取り除きたい場合。マージンを完全かつ永遠に取り除きたい場合は、matplotlib rc fileの行を変更することをお勧めします。


あるいは余白を変更する、 plt.xlim(..)又は ax.set_xlim(..)手動残さないホワイトスペースがないように、軸の制限を設定するために使用します。

+0

ありがとうございました。私はドキュメントのマージンを見逃していました。私が使用していた本は、テキストにコードのビットがなく、まだ空白がないので、なぜ空白があるのか​​混乱しました。 – lmurdock12

+0

まあ、0より大きいマージンは、matplotlib 2.0に新しく導入されました。以前のバージョンでは、質問は常に反対でした: "どうやってマージンを入れますか?"私はあなたが誰にも決して喜ばないと思う。 ;-)私はいくつかの情報を追加するように答えを更新しました。 – ImportanceOfBeingErnest

+0

2.0の前にmatplotlibを本当に復元するには、http://stackoverflow.com/questions/42713208/matplotlib-cancelling-the-offset-of-axis-introduced-in-matplotlib-2-0/42716384#42716384にご注意ください。 'plt.rcParams ['axes.autolimit_mode'] = 'round_numbers'が必要です。 – cqcn1991

関連する問題