如何在matplotlib中更改x轴,以便没有空白?

如何在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()


胡说叔叔
浏览 3496回答 3
3回答

Cats萌萌

在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(..)手动设置轴的限制,使之没有空白。

守着星空守着你

大于0的边距是新引入到matplotlib 2.0中的,所以在以前的版本中,问题总是相反的:“我如何在其中添加一些空白?”我想你永远不会取悦所有人。)我更新了答案,包括一些更多的信息。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python
MySQL