如何使用此数据框绘制时间序列?

4
我想把这个数据框绘制成时间序列,每个国家每年根据“计数”增加或减少一条线。我该怎么做?
        country  count
Year            
2005    Australia   2
2005    Austria     1
2005    Belgium     0
2005    Canada      4
2005    China       0
2006    Australia   3
2006    Austria     0
2006    Belgium     1
2006    Canada      5
2006    China       2
2007    Australia   5
2007    Austria     1
2007    Belgium     2
2007    Canada      6
2007    China       3

我希望有类似这样的东西: 在这里输入图片描述
4个回答

5
你可以使用 pd.pivot_tabledf.plot 来完成这个任务:
df.pivot_table(index='Year', columns='country', values='count').plot(xticks=df.Year.unique())

将返回

enter image description here


3
你可以使用 seaborn.lineplot:
import seaborn as sns

df.Year = pd.to_datetime(df.Year)

sns.set(rc={'figure.figsize':(12, 8)}) # changed the figure size to avoid overlapping
sns.lineplot(data=df, x=df['Year'].dt.strftime('%Y'), # show only years with strftime
             y=df['count'], hue='country') 

该技术提供输入图像描述


1
使用 seaborn 的好主意 +1 - T C Molenaar

3

使用 matplotlib(以及 seaborn 样式):

设置

import pandas as pd

data = {'Year': {0: 2005, 1: 2005, 2: 2005, 3: 2005, 4: 2005, 5: 2006,
                 6: 2006, 7: 2006, 8: 2006, 9: 2006, 10: 2007, 11: 2007, 
                 12: 2007, 13: 2007, 14: 2007}, 
        'country': {0: 'Australia', 1: 'Austria', 2: 'Belgium', 3: 'Canada', 
                    4: 'China', 5: 'Australia', 6: 'Austria', 7: 'Belgium', 
                    8: 'Canada', 9: 'China', 10: 'Australia', 11: 'Austria', 
                    12: 'Belgium', 13: 'Canada', 14: 'China'}, 
        'count': {0: 2, 1: 1, 2: 0, 3: 4, 4: 0, 5: 3, 6: 0, 7: 1, 8: 5, 9: 2, 
                  10: 5, 11: 1, 12: 2, 13: 6, 14: 3}}

df = pd.DataFrame(data)

图表

import matplotlib.pyplot as plt
import seaborn as sns

sns.set_style("dark")

df_pivot = df.pivot(index='Year', columns='country', values='count')

fig, ax = plt.subplots(figsize=(16,10))
ax.plot(df_pivot)
ax.grid()
ax.set_ylabel('Count')
ax.set_xlabel('Years')
ax.set_xticks(df_pivot.index.unique())
ax.legend(df_pivot.columns, title='Country count', fontsize=16)
plt.show()

结果:

plot

正如 Nuri Taş 的答案所示,seaborn可以为您完成很多这方面的"工作"。但是了解实际操作原理也是很有用的。


2

一个纯粹的pandas解决方案是使用pivotplot

df = pd.DataFrame({'Year':[2005,2005,2005,2005,2005,
                        2006,2006,2006,2006,2006,
                       2007,2007,2007,2007,2007],
                 'country' : ['Australia', 'Austria','Belgium', 'Canada', 'China']*3,
                 'count':[2,1,0,4,0,3,0,1,5,2,5,1,2,6,3]})

df.pivot(index='Year', columns='country', values='count').plot(xticks=df['Year'].unique())

导致的结果是:

在此输入图片描述


你需要 values='count' 对吗? - T C Molenaar
你说得对,这样做可以使图表更易读(特别是图例),并提高代码的可读性。 - TiTo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接