如何更改matplotlib中的x軸,以便沒有空格?因此,目前正在學習如何導入數據并在matplotlib中使用它,我甚至遇到了麻煩,即使我從本書中獲得了確切的代碼。這是情節的樣子,但我的問題是如何在x軸的開始和結束之間沒有空白的地方得到它。這是代碼:import csvfrom matplotlib import pyplot as pltfrom 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()
2 回答

PIPIONE
TA貢獻1829條經驗 獲得超9個贊
在matplotlib 2.x中,邊緣處設置了自動邊距,這可確保數據非常適合軸刺。在這種情況下,在y軸上可能需要這樣的余量。默認情況下,它以0.05
軸跨度為單位設置。要將邊距設置為0
x軸,請使用
plt.margins(x=0)
要么
ax.margins(x=0)
取決于具體情況。另請參閱文檔。
如果您想要刪除整個腳本中的邊距,您可以使用
plt.rcParams['axes.xmargin'] = 0
在腳本的開頭(y
當然是相同的)。如果要完全永久地刪除邊距,可能需要更改matplotlib rc文件中的相應行。
或者更改邊距,使用plt.xlim(..)
或ax.set_xlim(..)
手動設置軸的限制,使得沒有剩余空白區域。

繁華開滿天機
TA貢獻1816條經驗 獲得超4個贊
那么大于0的邊距是新引入matplotlib 2.0的,所以在以前的版本中,問題總是相反的:“我如何設置一些邊距?”。我猜你永遠不能取悅所有人。;-)我更新了答案以包含更多信息。
添加回答
舉報
0/150
提交
取消