您可以使用主要和次要定位器接近您想要的内容,DateFormatter
如下所示:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates
dr= pd.date_range("2014-01-01", "2017-06-30", freq="D")
df = pd.DataFrame({"dates":dr, "num":np.cumsum(np.random.randn(len(dr)))})
df["dates"] = pd.to_datetime(df["dates"])
fig, ax = plt.subplots()
ax.plot(df.dates, df.num)
ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator())
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator([1,7]))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%b\n%Y"))
plt.show()
要仅显示一月份的年份,而不显示其他月份的年份,您可能需要将DateFormatter
class MyMonthFormatter(matplotlib.dates.DateFormatter):
def __init__(self, fmt="%b\n%Y", fmt2="%b", major=[1], tz=None):
self.fmt2 = fmt2
self.major=major
matplotlib.dates.DateFormatter.__init__(self, fmt, tz=tz)
def __call__(self, x, pos=0):
if x == 0: raise ValueError('Error')
dt = matplotlib.dates.num2date(x, self.tz)
if dt.month in self.major:
return self.strftime(dt, self.fmt)
else:
return self.strftime(dt, self.fmt2)
ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator())
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator([1,7]))
ax.xaxis.set_major_formatter(MyMonthFormatter())
plt.show()