【问题标题】:Plot with two rows label sticks using matplotlib使用 matplotlib 绘制两行标签棒
【发布时间】:2018-01-16 05:01:30
【问题描述】:

我想使用 matplotlib.pyplot 绘制一个情节,其中 xticks 排列成两行几个月和几年,如下图所示。我做了那个情节,只是使用dataframe.plot(),即最简单的熊猫情节。

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

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

我得到了这个情节的 xticks 标签

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

【问题讨论】:

    标签: python matplotlib plot ticker dateformatter


    【解决方案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()
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      相关资源
      最近更新 更多