【问题标题】:Formatting dates on pandas timeseries plot messes up the date在熊猫时间序列图上格式化日期会弄乱日期
【发布时间】:2020-11-11 14:17:04
【问题描述】:

我正在尝试在索引为时间序列的数据框中格式化日期。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


periods = 30
df = pd.DataFrame(np.random.randint(0, 20, size=periods),
                  columns=["Value"],
                  index=pd.date_range("20180306", periods=periods))
ax = df.plot(kind='bar')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d %Y'))
plt.show()

问题:X 轴上的日期从纪元开始,因此图表将“1970 年 1 月 1 日”显示为第一个日期。

请注意,如果我不使用“条形”绘图类型,这个问题就会消失。

知道如何解决这个问题吗?

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

显然,日期格式和条形图存在一些问题。这是一个解决方法:

import matplotlib.dates as mdates

periods = 30
df = pd.DataFrame(np.random.randint(0, 20, size=periods),
                  columns=["Value"],
                  index=pd.date_range("20180306", periods=periods))
ax = df.plot(kind='bar')
plt.gca().xaxis.set_major_formatter(plt.FixedFormatter(df.index.to_series().dt.strftime('%b %d %Y')))

plt.show()

输出是:

【讨论】:

    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 2020-11-16
    • 2020-02-21
    • 2019-07-19
    • 2022-06-13
    • 2019-02-24
    • 1970-01-01
    相关资源
    最近更新 更多