简体   繁体   English

如何延长 matplotlib 的 x 轴

[英]How to extend the x-axis for matplotlib

I have a code given below:我有下面给出的代码:

import pandas as pd
import plotly.offline as py
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import matplotlib.patches as mpatches
import matplotlib.dates as mdates
import matplotlib as mpl

df = pd.read_csv(".\AirPassengers.csv")
df['Month'] = pd.to_datetime(df['Month'])
df.set_index('Month', inplace=True, drop=True)

fig, ax1 = plt.subplots(figsize=(20, 5))
ax1.plot(df.index, df["Passengers"].values, linestyle='-', marker='o', color='b', linewidth=2, label='Passenger Number')
fig.autofmt_xdate()
ax1.xaxis.set_major_locator(mdates.YearLocator())
ax1.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))

ax1.set_title("Passenger Number")
ax1.legend(loc="center left", bbox_to_anchor=(1.0, 0.5))
ax1.set_xlabel("Time Interval")
plt.tight_layout()

I am trying to extend x-axis or time interval more than 1960-12 independent of period of data.我试图独立于数据周期将 x 轴或时间间隔延长到 1960-12 年以上。 Can you please help me on it?你能帮我吗?

在此处输入图像描述

The easiest and most reliable method is to extend the original data by the desired time-series period and fill in the missing data with NA .最简单和最可靠的方法是将原始数据扩展所需的时间序列周期,并用NA填充缺失的数据。 Specify the start date of the data and the end date of the data with set_xlim() , as described in the comments in the graph-side processing.使用set_xlim()指定数据的开始日期和数据的结束日期,如图形端处理中的注释中所述。

df['Month'] = pd.to_datetime(df['Month'])
df.set_index('Month', inplace=True, drop=True)
# update 
new_index = pd.date_range(df.index[0], '1973-01-01', freq='MS')
df = df.reindex(new_index, fill_value=np.nan)

.
.
.

# update
ax1.set_xlim(df.index[0],df.index[-1])
plt.tight_layout()

plt.show()

在此处输入图像描述

The following worked for me:以下对我有用:

from dateutil.relativedelta import relativedelta

Then:然后:

ax.set_xlim(df.index[0], df.index[-1] + relativedelta(years=2))

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

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