gpt4 book ai didi

python - 轴标签的 Matplotlib DateFormatter 不起作用

转载 作者:太空狗 更新时间:2023-10-29 17:05:45 25 4
gpt4 key购买 nike

我正在尝试调整 x 轴的日期刻度标签的格式,以便它只显示年和月的值。根据我在网上找到的内容,我必须使用 mdates.DateFormatter,但它在我当前的代码中根本没有生效。有人看到问题出在哪里吗? (日期是 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()

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

最佳答案

pandas 不能很好地处理自定义日期时间格式。

在这种情况下,您只需要使用原始 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 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33743394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com