我正在尝试使用以下 python pandas 信息创建折线图: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 轴或将学生作为 y 轴)。
最佳答案
在使用 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()
关于python pandas plot 系列 matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51717881/