Python 如何更改 matplotlib 中的 x 轴,以便没有空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42045767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change the x axis in matplotlib so there is no white space?
提问by lmurdock12
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.
所以目前正在学习如何导入数据并在 matplotlib 中使用它,即使我有书中的确切代码,我也遇到了麻烦。
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.
这就是情节的样子,但我的问题是如何在 x 轴的起点和终点之间没有空白的地方得到它。
Here is the code:
这是代码:
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()
回答by ImportanceOfBeingErnest
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
在 matplotlib 2.x 中,边缘设置了一个自动边距,以确保数据很好地适合轴脊。在这种情况下,y 轴上可能需要这样的边距。默认情况下,它设置为0.05
以轴跨度为单位。要将边距设置为0
在 x 轴上,请使用
plt.margins(x=0)
or
或者
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
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:
在脚本的开头(y
当然也一样)。如果您想完全永久地摆脱边距,您可能需要更改matplotlib rc 文件中的相应行:
axes.xmargin : 0
axes.ymargin : 0
或者更改边距,使用
plt.xlim(..)
plt.xlim(..)
或ax.set_xlim(..)
ax.set_xlim(..)
手动设置轴的限制,以便没有空白。