Pandas具有便利的pandas.DataFrame.plot功能,它将使用Matplotlib绘制DataFrame的所有列。我经常发现自己使用DatetimeIndex,因此生成的图共享相同的datetime x轴。但是,我也经常想使用Matplotlib DateFormatter格式化结果图上的刻度标签。看来这是不可能的...
为了显示我的问题,请看一些示例代码:
import matplotlib.dates as dates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig, ax = plt.subplots(nrows=3, figsize=(8, 11))
# Create DataFrame with random data
df = pd.DataFrame({"foo": np.random.random(100), "bar": np.random.random(100)},
index=pd.date_range("2020-01-01", freq="D", periods=100))
# First method
df.plot(ax=ax[0])
ax[0].set_title("df.plot()")
# Second method
df.plot(ax=ax[1])
ax[1].xaxis.set_major_formatter(dates.DateFormatter("%Y-%m-%d"))
ax[1].set_title('ax = df.plot(); ax.xaxis.set_major_formatter(dates.DateFormatter("%Y-%m-%d"))')
# Third method
ax[2].plot_date(df.index, df["foo"].values, fmt="-", label="foo")
ax[2].plot_date(df.index, df["bar"].values, fmt="-", label="bar")
pd.DatetimeIndex
ax[2].xaxis.set_major_formatter(dates.DateFormatter("%Y-%m-%d"))
ax[2].set_title('ax.plot_date(df.index, df["foo"]); ax.plot_date(df.index, df["bar"])\nax.xaxis.set_major_formatter(dates.DateFormatter("%Y-%m-%d"))')
ax[2].legend()
# Rotate ticklabels in all plots
for ax in fig.get_axes():
ax.tick_params(rotation=45)
plt.tight_layout()
如您所见,第一个图上的次要刻度位置并不完美,但是日期符号至少是正确的。
在第二个图中,我尝试使用matplotlib DateFormatter来更好地控制日期的实际显示方式,但是注明的日期是完全错误的。此外,由于年份需要大于1900,所以使用%y代替%Y会在Windows计算机上引发错误。
在第三个绘图中,我跳过了Pandas内置的绘图功能,直接使用Matplotlib,使用完全相同的技术来格式化日期刻度标签。正是我想要的,它以我自己定义的方式显示了正确的日期。
我还已经尝试过使用pandas.DatetimeIndex.to_pydatetime和pandas.Timestamp的to_pydatetime,to_datetime64,to_numpy和to_julian_date函数将DataFrame的索引转换为各种日期时间,但无济于事。
是否有可能控制熊猫图如何注释DatetimeIndex的日期时间值?还是我坚持使用Matplotlib手动创建图?
基本上:我可以使用pd.DataFrame.plot()而不是plt.plot_date()获得第三次绘制的结果吗?