使用matplotlib绘制两行标签棒

时间:2017-08-08 14:45:47

标签: python matplotlib plot ticker dateformatter

我想有一个使用matplotlib.pyplot的情节,xticks排成两行数月和数年,如下图所示。我做了那个情节,只使用dataframe.plot(),即最简单的熊猫情节。 enter image description here

当我使用此代码执行绘图时(因为我需要添加另一个子绘图,这是不使用dataframe.plot()的原因),我如何获得xticks标签的before设置?

import matplotlib.pyplot as plt
figure, ax = plt.subplots()
ax.plot(xdata, ydata)

我为这个情节得到了这个xticks标签 enter image description here

我尝试使用matplotlib.dates.DateFormattermatplotlib.ticker,但我无法找到正确的设置

1 个答案:

答案 0 :(得分:1)

您可以使用主要和次要定位器以及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()

enter image description here

要仅显示1月份的年份,而不显示其他月份的年份,您可能需要继承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()

enter image description here