def add_stats_to_figure(fig, df, y_axis, chart_type): # Calculate statistics min_val = df[y_axis].min() max_val = df[y_axis].max() avg_val = df[y_axis].mean() median_val = df[y_axis].median() std_dev_val = df[y_axis].std() # Stats summary text stats_text = ( f"📊 **Statistics**\n\n" f"- **Min:** ${min_val:,.2f}\n" f"- **Max:** ${max_val:,.2f}\n" f"- **Average:** ${avg_val:,.2f}\n" f"- **Median:** ${median_val:,.2f}\n" f"- **Std Dev:** ${std_dev_val:,.2f}" ) # Charts suitable for stats annotations if chart_type in ["bar", "line", "scatter"]: # Add annotation box fig.add_annotation( text=stats_text, xref="paper", yref="paper", x=1.05, y=1, showarrow=False, align="left", font=dict(size=12, color="black"), bordercolor="black", borderwidth=1, bgcolor="rgba(255, 255, 255, 0.8)" ) # Add horizontal lines for min, median, avg, max fig.add_hline(y=min_val, line_dash="dot", line_color="red", annotation_text="Min", annotation_position="bottom right") fig.add_hline(y=median_val, line_dash="dash", line_color="orange", annotation_text="Median", annotation_position="top right") fig.add_hline(y=avg_val, line_dash="dashdot", line_color="green", annotation_text="Avg", annotation_position="top right") fig.add_hline(y=max_val, line_dash="dot", line_color="blue", annotation_text="Max", annotation_position="top right") elif chart_type == "box": # Box plots already show distribution (no extra stats needed) pass elif chart_type == "pie": # Pie charts don't need statistical overlays st.info("📊 Pie charts focus on proportions. No additional stats displayed.") else: st.warning(f"⚠️ No stats added for unsupported chart type: {chart_type}") return fig