+-
python – 用于轴标签的Matplotlib DateFormatter不起作用
我正在尝试调整x轴日期刻度标签的格式,以便它只显示年份和月份值.根据我在网上发现的内容,我必须使用mdates.DateFormatter,但它现在的代码并没有生效.有谁知道问题出在哪里? (日期是大熊猫Dataframe的索引)

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

fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

basicDF['some_column'].plot(ax=ax, kind='bar', rot=75)

ax.xaxis_date()

enter image description here

可重现的场景代码:

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

rng = pd.date_range('1/1/2014', periods=20, freq='m')

blah = pd.DataFrame(data = np.random.randn(len(rng)), index=rng)

fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

blah.plot(ax=ax, kind='bar')

ax.xaxis_date()

仍然不能只是出现年和月.

如果我在.plot之后设置格式,会得到如下错误:

ValueError: DateFormatter found a value of x=0, which is an illegal date. This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date().

如果我把它放在ax.xaxis_date()之前或之后,它也是一样的.

最佳答案
大熊猫不适用于自定义日期时间格式.

你需要在这种情况下使用原始的matplotlib.

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

N = 20
numpy.random.seed(N)

dates = pandas.date_range('1/1/2014', periods=N, freq='m')
df = pandas.DataFrame(
    data=numpy.random.randn(N), 
    index=dates,
    columns=['A']
)

fig, ax = plt.subplots(figsize=(10, 6))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.bar(df.index, df['A'], width=25, align='center')

这给了我:

enter image description here

点击查看更多相关文章

转载注明原文:python – 用于轴标签的Matplotlib DateFormatter不起作用 - 乐贴网