如何更改 x 轴以便没有空白?

2024-01-14

因此,目前正在学习如何导入数据并在 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()

边缘处设置了自动边距,确保数据很好地贴合在轴脊内。在这种情况下,y 轴上可能需要这样的边距。默认情况下它设置为0.05以轴跨度为单位。

将边距设置为0在 x 轴上,使用

plt.margins(x=0)

or

ax.margins(x=0)

取决于上下文。另请参阅文档 http://matplotlib.org/devdocs/api/_as_gen/matplotlib.axes.Axes.margins.html.

如果你想去掉整个脚本中的边距,你可以使用

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

在脚本的开头(与y当然)。如果您想完全永久地消除边距,您可能需要更改中的相应行matplotlib rc 文件 http://matplotlib.org/users/customizing.html:

axes.xmargin : 0
axes.ymargin : 0

Example

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
tips.plot(ax=ax1, title='Default Margin')
tips.plot(ax=ax2, title='Margins: x=0')
ax2.margins(x=0)

或者,使用plt.xlim(..) https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xlim.html or ax.set_xlim(..) https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xlim.html手动设置轴的限制,以便不留空白。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何更改 x 轴以便没有空白? 的相关文章

随机推荐