简体   繁体   中英

problems with set_major_locator in matplotlib

I have a AirlinePassenger dataset: https://github.com/jbrownlee/Datasets/blob/master/airline-passengers.csv .

I printed the dataset with given column:

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.set_index('Month', inplace=True, drop=True)

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

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

However, time interval is not printed: 在此处输入图像描述

Convert the month column, which is currently dtype object, to datetime.

Also, it would be good to use the object-oriented interface consistently (eg ax1.plot , not plt.plot ):

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

Output:

在此处输入图像描述

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