Torn.com-ActivityTracker/app/analysis/plot_line_activity-user.py
Michael Beck 5e98a0ba47 init
2025-02-22 16:55:41 +01:00

68 lines
2.4 KiB
Python

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from .basePlotAnalysis import BasePlotAnalysis
from flask import current_app, url_for
import matplotlib
matplotlib.use('Agg')
class PlotLineActivityAllUsers(BasePlotAnalysis):
"""
Class for analyzing user activity trends over multiple days and generating a line graph.
Attributes:
name (str): The name of the analysis.
description (str): A brief description of the analysis.
plot_filename (str): The filename for the output plot.
note (str): Additional notes for the analysis.
"""
name = "Activity Line Graph (All Users)"
description = "This analysis shows the activity line graph for all users. Gneerates a downloadable PNG image."
plot_filename = "line_activity-all_users.png"
note = ""
def transform_data(self, df: pd.DataFrame) -> pd.DataFrame:
"""
Transform data for the line plot.
Parameters:
df (pd.DataFrame): The input DataFrame containing user activity data.
Returns:
pd.DataFrame: The transformed DataFrame with activity counts by hour.
"""
df['hour'] = df['timestamp'].dt.hour
df = df[df['was_active'] == True].pivot_table(index='name', columns='hour', values='was_active', aggfunc='sum', fill_value=0)
df['total_active_minutes'] = df.sum(axis=1)
df = df.sort_values(by='total_active_minutes', ascending=False).drop('total_active_minutes', axis=1)
cumulative_sum_row = df.cumsum().iloc[-1]
df.loc['Cumulative Sum'] = cumulative_sum_row
return df
def plot_data(self, df: pd.DataFrame):
"""
Generate line graph for user activity throughout the day.
Parameters:
df (pd.DataFrame): The transformed DataFrame containing activity counts by hour.
"""
plt.figure(figsize=(12, 6))
# Plot each user's activity
for index, row in df.iterrows():
if index == 'Cumulative Sum':
plt.plot(row.index, row.values, label=index, linewidth=3, color='black') # Bold line for cumulative sum
else:
plt.plot(row.index, row.values, label=index)
# Add labels and title
plt.xlabel('Hour of Day')
plt.ylabel('Activity Count')
plt.title('User Activity Throughout the Day')
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.grid(True)