import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots from .basePlotlyAnalysis import BasePlotlyAnalysis from flask import current_app, url_for class PlotlyLineActivityAllUsers(BasePlotlyAnalysis): """ Class for analyzing user activity trends over multiple days and generating an interactive 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, Interactive)" description = "This analysis shows the activity line graph for all users. The graph is interactive and can be used to explore the data." plot_filename = "line_activity-all_users.html" 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 interactive line graph for user activity throughout the day. Parameters: df (pd.DataFrame): The transformed DataFrame containing activity counts by hour. """ self.fig = make_subplots() # Plot each user's activity for index, row in df.iterrows(): if index == 'Cumulative Sum': self.fig.add_trace(go.Scatter(x=row.index, y=row.values, mode='lines', name=index, line=dict(width=3, color='black'))) # Bold line for cumulative sum else: self.fig.add_trace(go.Scatter(x=row.index, y=row.values, mode='lines', name=index)) self.fig.update_layout( title='User Activity Throughout the Day', xaxis_title='Hour of Day', yaxis_title='Activity Count', legend_title='User', legend=dict(x=1, y=1), template='plotly_white' )