如何更改matplotlib中的x轴,以便没有空格?

lmu*_*k12 23 python matplotlib

因此,目前正在学习如何导入数据并在matplotlib中使用它,我甚至遇到了麻烦,即使我从本书中获得了确切的代码.

在此输入图像描述

这是情节的样子,但我的问题是如何在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()
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 43

在matplotlib 2.x中,边缘处设置了自动边距,这可确保数据在轴刺内很好地拟合.在这种情况下,在y轴上可能需要这样的余量.默认情况下,它以0.05轴跨度为单位设置.要将边距设置为0x轴,请使用

plt.margins(x=0)
Run Code Online (Sandbox Code Playgroud)

要么

ax.margins(x=0)
Run Code Online (Sandbox Code Playgroud)

取决于具体情况.另请参阅文档.

如果您想要删除整个脚本中的边距,您可以使用

plt.rcParams['axes.xmargin'] = 0
Run Code Online (Sandbox Code Playgroud)

在脚本的开头(y当然是相同的).如果要完全永久地删除边距,可能需要更改matplotlib rc文件中的相应行.


或者更改边距,使用plt.xlim(..)ax.set_xlim(..)手动设置轴的限制,使得没有剩余空白区域.

  • 好吧,大于 0 的边距是 matplotlib 2.0 新引入的,所以在以前的版本中,问题总是相反:“我如何放入一些边距?”。我想你永远无法取悦所有人。;-) 我更新了答案以包含更多信息。 (2认同)