import pandas as pd import plotly.express as px import plotly.graph_objs as go def plot_matches_by_period(matches, frequency='W'): """ Plots the number of matches by a specified time period (weekly or monthly) with growth rate annotations. Parameters: - matches: DataFrame or list of match data - frequency: 'W' for weekly, 'M' for monthly """ df = pd.DataFrame(matches) # Convert timestamps to datetime df['datetime'] = pd.to_datetime(df['datetime']) # Extracting the period (week or month) from the datetime period_format = 'W' if frequency == 'W' else 'M' df['period'] = df['datetime'].dt.to_period(period_format) # Grouping data by the specified period matches_per_period = df.groupby('period').size() # Calculating percentage growth from period to period growth = matches_per_period.pct_change() * 100 # Convert Period index to string for plotting matches_per_period.index = matches_per_period.index.astype(str) # Plotting using Plotly title_frequency = 'Weekly' if frequency == 'W' else 'Monthly' fig = px.bar(matches_per_period, x=matches_per_period.index, y=matches_per_period.values, labels={'y': 'Number of Matches', 'period': title_frequency}) fig.update_layout(title=f'Number of Matches Per {title_frequency}', xaxis_title=title_frequency, yaxis_title='Number of Matches') # Add annotations for growth percentages for idx, val in enumerate(matches_per_period.index): if pd.notna(growth.iloc[idx]): fig.add_annotation( x=val, y=matches_per_period.values[idx], text=f"{growth.iloc[idx]:.2f}%", showarrow=False, yshift=10 ) fig.show()