我有一个带有DatetimeIndex的数据框,如下所示:
In [3]: index = pd.date_range('September 1 2014', 'September 1 2015', freq='M')
...: index
Out[3]:
DatetimeIndex(['2014-09-30', '2014-10-31', '2014-11-30', '2014-12-31',
'2015-01-31', '2015-02-28', '2015-03-31', '2015-04-30',
'2015-05-31', '2015-06-30', '2015-07-31', '2015-08-31'],
dtype='datetime64[ns]', freq='M'
在不更改x刻度标签或显式日期格式的情况下进行绘图会产生0-12的x轴。
我的图包含一列中的13个子图。在绘制完所有子图之后,我尝试使用代码末尾的AutoDateLocator()在最后一个图上设置x轴:
fig.axes[-1].xaxis.set_major_locator(mdates.AutoDateLocator())
返回以下错误:
ValueError: ordinal must be >= 1
我尝试按照建议的here转换带有dates2num的数据框索引,但它产生了相同的结果:
df.index = mdates.date2num(df.index.to_pydatetime())
我尝试查阅文档,但我无法挖掘任何其他方法使matplotlib将x轴识别为日期。
以下是完整的代码:
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
index = pd.date_range('September 1 2014', 'September 1 2015', freq='M')
data = np.random.random([12, 13])
df = DataFrame(data=data, index=index)
# Draw figure
fig = plt.figure(figsize=(19,20), dpi=72)
fig.suptitle('Chart', fontsize=40, color='#333333')
# Draw charts
for i in range(0, len(df)):
ax = plt.subplot(len(df),1, i+1)
# Set ticks and labels
ax.tick_params(direction='in', length=45, pad=60,colors='0.75')
ax.yaxis.set_tick_params(size=0)
ax.set_yticklabels([])
ax.set_ylim([0, 2])
plt.ylabel(df.columns[i], rotation=0, labelpad=60, fontsize=20, color='#404040')
# Remove spines
sns.despine(ax=ax, bottom=True)
# Draw baseline, data, and threshold lines
# Threshold
ax.axhline(1.6, color='#a0db8e', linestyle='--', label='Threshold')
# Draw baseline
ax.axhline(1, color='0.55',label='Enterprise')
# Plot data
ax.plot(df.iloc[:, i], color='#14509f',label='Data')
# Subplot spacing
fig.subplots_adjust(hspace=1)
# Hide tick labels and first/last tick lines
plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)
plt.setp([a.get_xticklines()[-2:] for a in fig.axes],visible=False)
# Date in x-axis
fig.axes[-1].xaxis.set_major_locator(mdates.AutoDateLocator())
fig.axes[-1].xaxis.set_major_formatter(mdates.DateFormatter('%Y.%m.%d'))