John
John

Reputation: 503

python pandas plot series matplotlib

I am trying to create a line graph using the following python pandas information: index which is the date/period, 'student' which is the number of students who have visited per period and region which is where the students are visiting from. Ideally, I would like the number of students on the y axis, the date on the x axis and the region to be a different color or at least a different line associated with each region:

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

I am having trouble finding examples of being able to utilize a dataframe series (i.e., vs having to list each element explicitly and instead reference the index as the x axis or student as the y axis) by name.

Upvotes: 3

Views: 2221

Answers (1)

sacuL
sacuL

Reputation: 51335

You can iterate through your groups after you use groupby to group your data by Region, then plot each one. Here is a basic scaffold of code that you can build on:

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

Upvotes: 2

Related Questions