Python 轴标签的 Matplotlib DateFormatter 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33743394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib DateFormatter for axis label not working
提问by SpicyClubSauce
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)
我正在尝试调整 x 轴的日期刻度标签的格式,以便它只显示年和月值。从我在网上找到的内容来看,我必须使用mdates.DateFormatter
,但是对于我当前的代码,它根本没有生效。有人看到问题出在哪里了吗?(日期是熊猫数据框的索引)
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()
Reproducible scenario code:
可重现的场景代码:
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.
仍然不能只显示年份和月份。
If I set the format after .plot , get an error like this:
如果我在 .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 a
x.xaxis_date()
.
ValueError: DateFormatter 发现 x=0 的值,这是一个非法日期。这通常是因为您没有通知轴它正在绘制日期,例如,使用
x.xaxis_date()
.
It's the same for if I put it before ax.xaxis_date() or after.
如果我把它放在 ax.xaxis_date() 之前或之后,它是一样的。
采纳答案by Paul H
pandas just doesn't work well with custom date-time formats.
pandas 不适用于自定义日期时间格式。
You need to just use raw matplotlib in cases like this.
在这种情况下,您只需要使用原始 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')
And that gives me:
这给了我:
回答by Cilantro Ditrek
The accepted answerclaims that "pandas won't work well with custom date-time formats", but you can make use of pandas' to_datetime()
function to use your existing datetime Series in the dataframe:
接受的答案声称“pandas 不适用于自定义日期时间格式”,但您可以利用 pandas 的to_datetime()
功能在数据框中使用现有的日期时间系列:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
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=pd.to_datetime(rng))
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(DateFormatter('%m-%Y'))
ax.bar(blah.index, blah[0], width=25, align='center')
Will result in:
会导致:
You can see the different available formats here.
您可以在此处查看不同的可用格式。