pandas 在 matplotlib pyplot 中绘制周期系列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44100429/
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
Plotting period series in matplotlib pyplot
提问by oammon
I'm trying to plot timeseries revenue data by quarter with matplotlib.pyplot but keep getting an error. Below is my code and the errors The desired behavior is to plot the revenue data by quarter using matplotlib. When I try to do this, I get:
我正在尝试使用 matplotlib.pyplot 按季度绘制时间序列收入数据,但一直出现错误。下面是我的代码和错误所需的行为是使用 matplotlib 按季度绘制收入数据。当我尝试这样做时,我得到:
TypeError: Axis must have
freqset to convert to Periods
TypeError: Axis must have
频率set to convert to Periods
Is it because timeseries dates expressed as periods cannot be plotted in matplotlib? Below is my code.
是因为无法在 matplotlib 中绘制以句点表示的时间序列日期吗?下面是我的代码。
def parser(x):
return pd.to_datetime(x, format='%m%Y')
tot = pd.read_table('C:/Desktop/data.txt', parse_dates=[2], index_col=[2], date_parser=parser)
tot = tot.dropna()
tot = tot.to_period('Q').reset_index().groupby(['origin', 'date'], as_index=False).agg(sum)
tot.head()
origin date rev
0 KY 2016Q2 1783.16
1 TN 2014Q1 32128.36
2 TN 2014Q2 16801.40
3 TN 2014Q3 33863.39
4 KY 2014Q4 103973.66
plt.plot(tot.date, tot.rev)
回答by Patrick Hingston
If you want to use matplotlib, the following code should give you the desired plot:
如果你想使用 matplotlib,下面的代码应该给你想要的图:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'origin': ['KY','TN','TN','TN','KY'],
'date': ['2016Q2','2014Q1','2014Q2','2014Q3','2014Q4'],
'rev': [1783.16, 32128.36, 16801.40, 33863.39, 103973.66]})
x = np.arange(0,len(df),1)
fig, ax = plt.subplots(1,1)
ax.plot(x,df['rev'])
ax.set_xticks(x)
ax.set_xticklabels(df['date'])
plt.show()
You could use the xtickscommand and represent the data with a bar chart with the following code:
您可以使用xticks命令并使用以下代码用条形图表示数据:
plt.bar(range(len(df.rev)), df.rev, align='center')
plt.xticks(range(len(df.rev)), df.date, size='small')
回答by jezrael
It seems like bug.
好像是bug。
For me works DataFrame.plot
:
对我来说有效DataFrame.plot
:
ooc.plot(x='date', y='rev')