简体   繁体   English

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

[英]How can I change the x axis in matplotlib so there is no white space?

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.这就是 plot 的样子,但我的问题是如何在 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()

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.在这种情况下,在 y 轴上可能需要这样的余量。 By default it is set to 0.05 in units of axis span.默认情况下,它以轴跨度为单位设置为0.05

To set the margin to 0 on the x axis, use要将 x 轴上的边距设置为0 ,请使用

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).在脚本的开头(当然y也是如此)。 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 :如果您想完全永久地消除边距,您可能需要更改matplotlib rc 文件中的相应行:

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)

在此处输入图像描述


Alternatively, use plt.xlim(..) or ax.set_xlim(..) to manually set the limits of the axes such that there is no white space left.或者,使用plt.xlim(..)ax.set_xlim(..)手动设置轴的限制,以便没有剩余空白。

If you only want to remove the margin on one side but not the other, eg remove the margin from the right but not from the left, you can use set_xlim() on a matplotlib axes object.如果您只想删除一侧而不是另一侧的边距,例如从右侧而不是从左侧删除边距,您可以在 matplotlib 轴对象上使用set_xlim()

import seaborn as sns
import matplotlib.pyplot as plt
import math

max_x_value = 100

x_values = [i for i in range (1, max_x_value + 1)]
y_values = [math.log(i) for i in x_values] 

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
sn.lineplot(ax=ax1, x=x_values, y=y_values)
sn.lineplot(ax=ax2, x=x_values, y=y_values)
ax2.set_xlim(-5, max_x_value) # tune the -5 to your needs

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM