pfnuesel
pfnuesel

Reputation: 15310

Plot multiple lines from one DataFrame

I have the following DataFrame in Python Pandas:

df.head(3)

+===+===========+======+=======+
|   | year-month| cat  | count |
+===+===========+======+=======+
| 0 | 2016-01   |    1 |    14 |
+---+-----------+------+-------+
| 1 | 2016-02   |    1 |    22 |
+---+-----------+------+-------+
| 2 | 2016-01   |    2 |    10 |
+---+-----------+------+-------+

year-month is a combination of year and month, dating back about 8 years. cat is an integer from 1 to 10. count is an integer.

I now want to plot count vs. year-month with matplotlib, one line for each cat. How can this be done?

Upvotes: 0

Views: 60

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Easiest is seaborn:

import seaborn as sns

sns.lineplot(x='year-month', y='count', hue='cat', data=df)

Note: it might also help if you convert year-month to datetime type before plotting, e.g.

df['year-month'] = pd.to_datetime(df['year-month'], format='%Y-%m').dt.to_period('M')

Upvotes: 1

Related Questions