如何更改matplotlib中的x轴,以确保没有空格? [英] How can I change the x axis in matplotlib so there is no white space?

查看:100
本文介绍了如何更改matplotlib中的x轴,以确保没有空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当前正在学习如何在matplotlib中导入数据并使用它,即使在我拥有本书中的确切代码的情况下,我也遇到了麻烦.

So currently learning how to import data and work with it in matplotlib and I am having trouble even tho I have the exact code from the book.

这是情节的样子,但是我的问题是,如何在x轴的起点和终点之间没有空白的情况下得到它.

This is what the plot looks like, but my question is how can I get it where there is no white space between the start and the end of the x-axis.

这是代码:

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()

推荐答案

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

In matplotlib 2.x there is an automatic margin set at the edges, which ensures the data to be nicely fitting within the axis spines. In this case such a margin is probably desired on the y axis. By default it is set to 0.05 in units of axis span. To set the margin to 0 on the x axis, use

plt.margins(x=0)

ax.margins(x=0)

取决于上下文.另请参见文档.

depending on the context. Also see the documentation.

如果要在整个脚本中消除空白,可以使用

In case you want to get rid of the margin in the whole script, you can use

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

在脚本的开头(当然与y相同).如果要彻底摆脱空白,请更改 matplotlib rc中的相应行文件:

at the beginning of your script (same for y of course). If you want to get rid of the margin entirely and forever, you might want to change the according line in the matplotlib rc file:

axes.xmargin : 0
axes.ymargin : 0


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


Alternatively to changing the margins, use plt.xlim(..) or ax.set_xlim(..) to manually set the limits of the axes such that there is no white space left.

这篇关于如何更改matplotlib中的x轴,以确保没有空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆