0
$\begingroup$

Say I have a dataframe with date as index. I would like to plot a line plot of some values in a column A over a given time frame. Say for the month of August. In column A I have several entries for example for the 02/08/2020 and a four different values on 03/08/2020 and so I would like to plot the sum of those values.

Is there an easy one line that would do it?

$\endgroup$

1 Answer 1

2
$\begingroup$

You could aggregate and sum values in a single line by pandas groupby() function. Here's an example:

  1. Making a simple dummy dataset:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

values = np.random.randint(1, high=100, size=50)
df = pd.DataFrame(data=values, columns=['values'])
  1. Adding some dates as indices:
def get_days():
    return sorted(np.random.choice(range(1, 31), size=25, replace=True))

year = '2021'
months = ['08', '09']
dates = []
for month in months:
    days = get_days()
    for day in days:
        dates.append(f'{day}/{month}/{year}')

df.index = dates

Dataframe looks like the following:

head

  1. Aggregate and sum the data:
answers = df.groupby(df.index, sort=False).sum()  # since index already sorted

Printing answers:

head2

  1. Simply plot it
dates = answers.index 
sums = answers.values 

fig, ax = plt.subplots()

ax.plot(range(len(dates)), sums, 'ro-')
ax.set_xticks(range(0, len(dates), 3))       # need to adjust to ensure plot is readable
ax.set_xticklabels(dates[::3], rotation=90)
ax.set_xlabel("Dates")
ax.set_ylabel("Sums")
ax.set_title("Sum Over Dates")
plt.show();

The plot to the above code looks like the following:

plot

You can now control how you want to aggregate in several ways. You can add temporary columns as days, months, years and aggregate them hierarchically(and in a single line) if that is what you desire as shown here.

Plotting it in a single line will not only be difficult, but less readable too, so I'd suggest avoiding that.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.