【问题标题】:How can I change the x axis in matplotlib so there is no white space?如何更改 matplotlib 中的 x 轴以便没有空格?
【发布时间】:2017-06-22 02:17:00
【问题描述】:

所以目前正在学习如何在 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()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    在边缘设置了自动边距,以确保数据很好地适合轴脊。在这种情况下,在 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)
    


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

    【讨论】:

      【解决方案2】:

      如果您只想删除一侧而不是另一侧的边距,例如从右侧而不是从左侧删除边距,您可以在 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
      

      【讨论】:

        猜你喜欢
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        相关资源
        最近更新 更多