使用 matplotlib 绘制两行标签棒 [英] Plot with two rows label sticks using matplotlib

查看:88
本文介绍了使用 matplotlib 绘制两行标签棒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用matplotlib.pyplot作图,将xticks分两行排列几个月和几年,如下图所示.我做了那个图,只是使用 dataframe.plot(),即最简单的熊猫图.

I would like to have a plot using matplotlib.pyplot with the xticks arrange in two rows for months and years like the image following. I did that plot, just using dataframe.plot(), i.e. the simplest plot of pandas.

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

When I do the plot using this code (because I need to add another subplots and that is the reason to not use dataframe.plot()), how I can get the before settings for the xticks labels?

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

我得到了该图的xticks标签

I get this xticks labels for the plot

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

I tried using matplotlib.dates.DateFormatter and matplotlib.ticker but I can't find the right settings

推荐答案

您可以使用主要和次要定位符以及 DateFormatter 来接近所需的内容,

You can get close to what you want with the major and minor locators and a DateFormatter like this:

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

To only show the years for January, but not for other months, you may then need to subclass the 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()

这篇关于使用 matplotlib 绘制两行标签棒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆