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

发布于 2021-02-02 23:14:58

因此,当前正在学习如何在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()
关注者
0
被浏览
75
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

    plt.margins(x=0)
    

    要么

    ax.margins(x=0)
    

    取决于上下文。另请参阅文档。

    如果您想摆脱整个脚本中的空白,可以使用

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

    在脚本的开头(y当然也是一样)。如果要彻底摆脱空白,请永久更改matplotlib rc文件中的相应行:

    axes.xmargin : 0
    axes.ymargin : 0
    

    除了更改页边距之外,还可以使用plt.xlim(..)ax.set_xlim(..)手动设置轴的限制,以确保没有空白。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看