Plotting a cumulative graph of Python datetimes in Matplotlib

To plot a cumulative graph of Python datetimes in Matplotlib, you can combine Pandas datetime functionality with Matplotlib's plotting capabilities. This is useful for visualizing data trends over time, such as daily sales, website visits, or any time-series data that accumulates.

Basic Setup

First, let's create a dataset with datetime values and plot a cumulative sum ?

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import numpy as np

# Set figure size
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

# Create sample datetime data
start_date = datetime(2024, 1, 1)
dates = [start_date + timedelta(days=i) for i in range(30)]
values = np.random.randint(10, 100, 30)  # Random daily values

# Create DataFrame
df = pd.DataFrame({
    'date': dates,
    'daily_value': values,
    'cumulative': np.cumsum(values)
})

print(df.head())
        date  daily_value  cumulative
0 2024-01-01           84          84
1 2024-01-02           90         174
2 2024-01-03           11         185
3 2024-01-04           28         213
4 2024-01-05           89         302

Plotting the Cumulative Graph

Now let's create the cumulative plot with proper datetime formatting ?

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import numpy as np

# Create sample data
start_date = datetime(2024, 1, 1)
dates = [start_date + timedelta(days=i) for i in range(30)]
values = np.random.randint(10, 100, 30)

df = pd.DataFrame({
    'date': dates,
    'daily_value': values,
    'cumulative': np.cumsum(values)
})

# Create the plot
plt.figure(figsize=(12, 6))
plt.plot(df['date'], df['cumulative'], marker='o', linewidth=2, markersize=4, color='blue')

# Customize the plot
plt.title('Cumulative Values Over Time', fontsize=16, fontweight='bold')
plt.xlabel('Date', fontsize=12)
plt.ylabel('Cumulative Value', fontsize=12)
plt.grid(True, alpha=0.3)

# Format x-axis dates
plt.xticks(rotation=45)

# Tight layout to prevent label cutoff
plt.tight_layout()
plt.show()
[A line graph showing cumulative values increasing over time from January 1st to January 30th, 2024]

Real-World Example: College Admissions Over Years

Here's a practical example showing cumulative college admissions over multiple years ?

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime

# College admission data with actual datetime objects
admission_data = {
    'year': [datetime(2019, 1, 1), datetime(2020, 1, 1), datetime(2021, 1, 1), 
             datetime(2022, 1, 1), datetime(2023, 1, 1), datetime(2024, 1, 1)],
    'annual_admissions': [1200, 1350, 1100, 1450, 1600, 1750]
}

df = pd.DataFrame(admission_data)
df['cumulative_admissions'] = df['annual_admissions'].cumsum()

# Create the plot
plt.figure(figsize=(10, 6))
plt.plot(df['year'], df['cumulative_admissions'], 
         marker='s', linewidth=3, markersize=8, color='green', markerfacecolor='lightgreen')

plt.title('Cumulative College Admissions (2019-2024)', fontsize=16, fontweight='bold')
plt.xlabel('Year', fontsize=12)
plt.ylabel('Cumulative Admissions', fontsize=12)
plt.grid(True, alpha=0.3)

# Add value labels on points
for i, (x, y) in enumerate(zip(df['year'], df['cumulative_admissions'])):
    plt.annotate(str(y), (x, y), textcoords="offset points", xytext=(0,10), ha='center')

plt.tight_layout()
plt.show()

print("Final DataFrame:")
print(df)
Final DataFrame:
        year  annual_admissions  cumulative_admissions
0 2019-01-01               1200                   1200
1 2020-01-01               1350                   2550
2 2021-01-01               1100                   3650
3 2022-01-01               1450                   5100
4 2023-01-01               1600                   6700
5 2024-01-01               1750                   8450

Key Features for Datetime Plots

  • Date formatting: Use plt.xticks(rotation=45) for readable date labels

  • Cumulative calculation: Use np.cumsum() or df.cumsum()

  • Proper datetime objects: Use datetime() or pd.to_datetime()

  • Grid and styling: Add plt.grid(True, alpha=0.3) for better readability

Conclusion

Plotting cumulative graphs with Python datetimes requires combining Pandas for data manipulation and Matplotlib for visualization. Use cumsum() for cumulative calculations and proper datetime formatting for clear time-series plots.

Updated on: 2026-03-25T21:57:23+05:30

691 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements