Search code examples
pythonpandasmatplotlibgroup-by

How to plot based on sum amount each month


I made data frame shown below which has 3 companies A,B and C. Companies buy certain amount of vouchers during 2016 to 2018 period. Some days eg. Company A buys 100 pieces for $3000 other days no company buys any.

I'd like see how these three companies compare for last two years when it comes to money spent for vouchers so my ideas was following:

Sum all money spent each month for each company, and plot them in bar graph or just standard line - so three lines each with different color. Since its 2 years of data, there would be roughly 24 date-points on x axis

I tried something like: plt.bar(A['Datetime'], A['PaidTotal']) But get: ufunc subtract cannot use operands with types dtype('

But this is just for one company anyway not for all 3 in one graph (I can sort those dates, thats not a problem)

Company Name    PaidTotal   Datetime
585 CompanyA    218916.0    2016-10-14 10:51:07
586 CompanyB    430000.0    2017-01-23 11:05:08
591 CompanyB    546217.0    2016-09-26 14:20:00
592 CompanyC    73780.0     2016-12-07 07:52:01
593 CompanyA    132720.0    2016-10-04 16:14:10
595 CompanyC    52065.0     2016-11-12 14:32:40  

Solution

  • For a bar chart you can call df.groupby('Company Name')['PaidTotal'].sum().plot.bar():

    enter image description here

    To see a line chart of all three over time, you can try this (the axes are wrong, but this is the general idea):

    sums = df.groupby(['Company Name', 'Datetime'])['PaidTotal'].sum().reset_index(level=0)
    for company in sums['Company Name'].unique():
        sums[sums['Company Name'] == company]['PaidTotal'].plot();
    

    enter image description here