df.pivot_table(index='Year', columns='country', values='count').plot(xticks=df.Year.unique())
将返回
使用 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()
正如 Nuri Taş 的答案所示,seaborn
可以为您完成很多这方面的"工作"。但是了解实际操作原理也是很有用的。
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
seaborn
的好主意 +1 - T C Molenaar