gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:45:12 27 4
gpt4 key购买 nike

所以目前正在学习如何在 matplotlib 中导入数据并使用它,即使我有书中的确切代码,我也遇到了麻烦。

enter image description here

这就是情节的样子,但我的问题是如何在 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,以轴跨度为单位。

要将 x 轴上的边距设置为 0,请使用

plt.margins(x=0)

ax.margins(x=0)

取决于上下文。另见 the documentation .

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

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

在脚本的开头(当然 y 也是如此)。如果您想完全永久地消除边距,您可能需要更改 matplotlib rc file 中的相应行。 :

axes.xmargin : 0
axes.ymargin : 0

示例

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)

enter image description here


或者,使用 plt.xlim(..)ax.set_xlim(..)手动设置坐标轴的范围,以便没有剩余空间。

关于python - 如何更改 matplotlib 中的 x 轴以便没有空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42045767/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com