轴标签的 Matplotlib DateFormatter 不起作用 [英] Matplotlib DateFormatter for axis label not working

查看:42
本文介绍了轴标签的 Matplotlib DateFormatter 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调整 x 轴的日期刻度标签的格式,使其仅显示年和月值.从我在网上找到的内容来看,我必须使用 mdates.DateFormatter,但是对于我当前的代码,它根本没有生效.有人看到问题出在哪里了吗?(日期是熊猫数据框的索引)

I'm trying to adjust the formatting of the date tick labels of the x-axis so that it only shows the Year and Month values. From what I've found online, I have to use mdates.DateFormatter, but it's not taking effect at all with my current code as is. Anyone see where the issue is? (the dates are the index of the pandas 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()

可重现的场景代码:

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()

仍然不能只显示年份和月份.

Still can't get just the year and month to show up.

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

If I set the format after .plot , get an error like this:

ValueError: DateFormatter 发现 x=0 的值,这是一个非法日期.这通常是因为您没有通知轴它正在绘制日期,例如,使用 x.xaxis_date().

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() 之前或之后是一样的.

It's the same for if I put it before ax.xaxis_date() or after.

推荐答案

pandas 不适用于自定义日期时间格式.

pandas just doesn't work well with custom date-time formats.

在这种情况下,您只需要使用原始 matplotlib.

You need to just use raw matplotlib in cases like this.

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')

这给了我:

这篇关于轴标签的 Matplotlib DateFormatter 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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