Meghdeep Ray
Meghdeep Ray

Reputation: 5537

Python3 MatPlotLib : How can I get Multiple Line Plots

I have a list of Tuples like this :

list_months = [ ('A', 'January'),
                ('A', 'January'),
                ('A', 'January'),  # Total 10 instances of ('A', 'January')
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'February'),
                ('A', 'February'),
                .............
                ('B', 'January'),
                ('B', 'January'),  # Total 15 instances of ('B', 'January')
                ('B', 'July'),
                ('B', 'July'),
                ............. ]

This was obtained via a Pandas dataframe using :

for index, val in b['Incident Reported Date Time'].iteritems():
    list_months.append((index, str(val)))

I want to be able to generate a MatPlotLib graph such that :
X-Axis -> Months
Y-Axis -> Volume
Multiple Colored Lines -> Each representing 'A', 'B', 'C', etc.


enter image description here

For example in this picture the Red line would represent 'A' and the blue line 'B'.
Since there are 10 of ('A', 'January') it shows the red line on 10 at the Y-Axis for the month of January and there are 15 of ('B', January') so it shows the blue line at 15 at the Y-Axis for the month of January.

How can I generate this and the legend dynamically in matplotlib for Python3 ?
The graph should be line graphs like in the example image.

Upvotes: 0

Views: 482

Answers (1)

BrenBarn
BrenBarn

Reputation: 251578

It will be easier to plot if you leave the data in a DataFrame. I made a sample DataFrame using the example data from your post:

list_months = [ ('A', 'January'),
                ('A', 'January'),
                ('A', 'January'),  # Total 10 instances of ('A', 'January')
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'March'),
                ('A', 'February'),
                ('A', 'February'),
                ('B', 'January'),
                ('B', 'January'),  # Total 15 instances of ('B', 'January')
                ('B', 'July'),
                ('B', 'July')
            ]
d = pandas.DataFrame(list_months, columns=["Item", "Month"]).fillna(0)

>>> d
   Item     Month
0     A   January
1     A   January
2     A   January
3     A     March
4     A     March
5     A     March
6     A  February
7     A  February
8     B   January
9     B   January
10    B      July
11    B      July

Then you can get your plot easily:

>>> d.groupby(['Month', 'Item']).size().unstack().loc[['January', 'February', 'March', 'July']].fillna(0).plot(kind='line')

enter image description here

(The .loc['January', 'February', ...] bit is only necessarily to get the months in temporal order rather than alphabetical order. In the long run, you're probably better off storing this information via a datetime object or a number representing the month.)

Upvotes: 3

Related Questions