python - 使用 matplotlib 绘制两行标签贴

标签 python matplotlib plot ticker dateformatter

我想使用 matplotlib.pyplot 绘制一个图,其中 xticks 排列成两行数月和数年,如下图所示。我只使用 dataframe.plot() 绘制了该图,即最简单的 pandas 绘图。 enter image description here

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

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

我得到了该图的 xticks 标签 enter image description here

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

最佳答案

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

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

关于python - 使用 matplotlib 绘制两行标签贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571467/

相关文章:

python - 等高线图python中的长错误

python - ValueError : Length mismatch: Expected axis has 6 elements, 新值有 1 个元素

flutter - flutter 中的图形网络可视化?

python - Graph_Tool - 使用用户定义的顶点文本绘制图形

python - 如何在目录中的文件上运行gunicorn?

python-2.7 - 属性错误 : 'module' object has no attribute 'cm'

R 图 : Scaling node size

python - 如何在 SHAP 汇总图上绘制特定特征?

python - 未达到 Airflow 传感器超时

Python读取两个字符串之间的特定文本行