问题描述
我希望使用matplotlib绘制一个熊猫时间序列对象data
.对于简单的折线图data.plot()
,我可以使用ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d %H:%M:%S'))
成功更改x轴日期格式.
I wish to plot a pandas time-series object data
with matplotlib. For a simple line chart data.plot()
, I was able to successfully change the x-axis date format with ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d %H:%M:%S'))
.
但是,对于条形图data.plot(kind='bar')
,我无法执行相同的操作.并且该图表不会显示.有没有办法更改熊猫条形图的数据格式?我知道我可以使用plt.bar方法创建图表,但是我需要使用熊猫堆叠的条形图来获取更复杂的数据.
However, I am not able to do the same for a bar chart data.plot(kind='bar')
. And the chart wouldn't appear. Is there a way to change data format for pandas bar chart? I know I can create a chart with plt.bar method, but I need to use pandas stacked bar chart for more complicated data.
import matplotlib.pyplot as plt
import matplotlib.dates as md
import numpy as np
import pandas as pd
import datetime as dt
import time
n=20
duration=1000
now=time.mktime(time.localtime())
timestamps=np.linspace(now,now+duration,n)
dates=[dt.datetime.fromtimestamp(ts) for ts in timestamps]
values=np.sin((timestamps-now)/duration*2*np.pi)
data=pd.Series(values, index=dates)
fig=figure(figsize(5,5))
ax=fig.add_subplot(111)
data.plot(kind='bar')
ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d %H:%M:%S'))
推荐答案
由于熊猫只使用matplotlib,因此您当然可以使用matplotlib创建相同的(堆叠的)条形图.没有理由只能为此使用熊猫.
Since Pandas simply uses matplotlib you can of course create an identical (stacked) barchart with matplotlib. There is not reason why you can only use Pandas for that.
在这种情况下,它无济于事. Matplotlib的bar()
将xvalues从日期更改为浮点数,因此DateFormatter
不再起作用.您可以使用ax.get_xticks()
检查xticks.
Its not going to help in this case though. Matplotlib's bar()
changes the xvalues from dates to floats, therefore a DateFormatter
doesnt work anymore. You can check the xticks with ax.get_xticks()
.
我看不到如何使xticks成为日期,但是您可以自己覆盖xticklabels:
I dont see how you can make the xticks dates, but you can override the xticklabels yourself:
ax.set_xticklabels([dt.strftime('%Y-%m-%d %H:%M:%S') for dt in data.index.to_pydatetime()])
这篇关于无法在 pandas 条形图中调整x轴DateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!