你也可以格式化DateTimeIndex
“手动”使用大熊猫Timestamp
对象的属性的熊猫的x轴蜱和标签。
我发现,不是使用matplotlib.dates
定位器,其工作的其他日期时间格式比熊猫(如果我没有记错的话),因此有时会表现出奇怪的行为,如果日期没有相应转换容易得多。
这里是一个通用的例子,显示了基于Timestamp
对象大熊猫的属性每个月的第一天,作为一个标签:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# data
dim = 8760
idx = pd.date_range('1/1/2000 00:00:00', freq='h', periods=dim)
df = pd.DataFrame(np.random.randn(dim, 2), index=idx)
# select tick positions based on timestamp attribute logic. see:
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.html
positions = [p for p in df.index
if p.hour == 0
and p.is_month_start
and p.month in range(1, 13, 1)]
# for date formatting, see:
# https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
labels = [l.strftime('%m-%d') for l in positions]
# plot with adjusted labels
ax = df.plot(kind='line', grid=True)
ax.set_xlabel('Time (h)')
ax.set_ylabel('Foo (Bar)')
ax.set_xticks(positions)
ax.set_xticklabels(labels)
plt.show()
产量:
希望这有助于!
你是否将日期解析为日期时间? –
@DemetriP谢谢。看起来至少是问题的一部分。现在使用ax.xaxis.set_major_locator之后,我确实看到了蜱虫......唯一的问题是现在我每年只看到一个蜱虫。 我明显使用MonthLocator错误。 – Rotkiv