python画时间序列图折线图_在matplotlib图上绘制时间序列p的多条线

这可以通过以下步骤实现:从列标签中提取年份字符串

将年份字符串转换为日期时间

通过迭代groupby对象在同一轴上绘图。在

比如:from StringIO import StringIO

import matplotlib.pyplot as plt

import pandas as pd

df = pd.read_csv(StringIO("""name, employment_2007, employment_2008, employment_2016

Napa, 200, 230,215

Lake, 140, 130,150"""),sep=',',index_col=['name'])

#Get year string and convert to date time

df = df.unstack().reset_index()

df['Year'] = df['level_0'].str.split('_').apply(lambda x: x[1])

df['TimeStamp'] = pd.to_datetime(df['Year'],format='%Y')

#Get Rid of extra columns and rename series to plot

df = df[['name',0,'TimeStamp']]

df = df.rename(columns={0:'Employment'})

fig,ax= plt.subplots()

for n, group in df.groupby('name'):

group.plot(x='TimeStamp',y='Employment', ax=ax,label=n)

它产生了一个类似于:

你可能感兴趣的:(python画时间序列图折线图)