简体   繁体   中英

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. 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 . 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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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