python pandas plot系列matplotlib

时间:2018-08-07 02:15:05

标签: python pandas matplotlib

我正在尝试使用以下python熊猫信息创建折线图:index是日期/期间,“ student”是每个时期和地区访问过的学生人数,这是学生从哪里来的。理想情况下,我希望y轴上的学生人数,x轴上的日期以及该区域使用不同的颜色,或者至少与每个区域相关的线不同:

Year    Region    Student
2013    North     1
2013    South     2
2013    East      5
2014    North     3
2014    South     7
2014    East      10

我很难找到能够利用数据框系列的示例(即,相对于必须显式列出每个元素,而是将索引作为x轴或将Student作为y轴)。

1 个答案:

答案 0 :(得分:2)

使用groupby将数据按Region分组后,您可以遍历各个组,然后绘制每个组。这是可以构建的基本代码框架:

for region, data in df.groupby('Region'):
    plt.plot(data['Year'], data['Student'], label=region)

plt.xlabel('Year')
plt.ylabel('Number of Students')
plt.legend()
plt.show()

enter image description here