# 创建完整的成绩走势图分析
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 设置图形样式
plt.style.use('seaborn-v0_8-darkgrid')

# 使用之前的数据
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=20, freq='W')
scores = np.random.randint(60, 100, size=20)
scores = scores + np.linspace(0, 15, 20) + np.random.normal(0, 3, 20)
scores = np.clip(scores, 60, 100)

df = pd.DataFrame({'Date': dates, 'Score': scores})

# 计算移动平均
df['3_MA'] = df['Score'].rolling(window=3, min_periods=1).mean()
df['7_MA'] = df['Score'].rolling(window=7, min_periods=1).mean()

# 创建图表
fig, axs = plt.subplots(2, 2, figsize=(14, 10))

# 1. 主趋势图
axs[0, 0].plot(df['Date'], df['Score'], 'o-', linewidth=2, markersize=8, 
               color='#2E86AB', label='Original Scores')
axs[0, 0].plot(df['Date'], df['3_MA'], '--', linewidth=2, 
               color='#A23B72', label='3-Week MA')
axs[0, 0].plot(df['Date'], df['7_MA'], '-.', linewidth=2, 
               color='#F18F01', label='7-Week MA')
axs[0, 0].set_title('Score Trend Analysis', fontsize=14, fontweight='bold')
axs[0, 0].set_xlabel('Date')
axs[0, 0].set_ylabel('Score')
axs[0, 0].legend()
axs[0, 0].grid(True, alpha=0.3)
axs[0, 0].tick_params(axis='x', rotation=45)

# 2. 成绩分布直方图
axs[0, 1].hist(df['Score'], bins=8, edgecolor='black', alpha=0.7, color='#2E86AB')
axs[0, 1].axvline(df['Score'].mean(), color='red', linestyle='--', 
                  linewidth=2, label=f'Mean: {df["Score"].mean():.1f}')
axs[0, 1].set_title('Score Distribution', fontsize=14, fontweight='bold')
axs[0, 1].set_xlabel('Score')
axs[0, 1].set_ylabel('Frequency')
axs[0, 1].legend()
axs[0, 1].grid(True, alpha=0.3)

# 3. 累计平均分
cumulative_avg = df['Score'].expanding().mean()
axs[1, 0].plot(df['Date'], cumulative_avg, 's-', linewidth=2, 
               markersize=6, color='#3D5A80', label='Cumulative Average')
axs[1, 0].axhline(y=df['Score'].mean(), color='red', linestyle='--', 
                  alpha=0.5, label=f'Overall Mean: {df["Score"].mean():.1f}')
axs[1, 0].fill_between(df['Date'], cumulative_avg, alpha=0.3, color='#3D5A80')
axs[1, 0].set_title('Cumulative Average Score', fontsize=14, fontweight='bold')
axs[1, 0].set_xlabel('Date')
axs[1, 0].set_ylabel('Cumulative Average')
axs[1, 0].legend()
axs[1, 0].grid(True, alpha=0.3)
axs[1, 0].tick_params(axis='x', rotation=45)

# 4. 成绩变化率
score_change = df['Score'].pct_change() * 100
axs[1, 1].bar(df['Date'], score_change, color=np.where(score_change >= 0, 'green', 'red'), 
              alpha=0.6, edgecolor='black')
axs[1, 1].axhline(y=0, color='black', linestyle='-', linewidth=1)
axs[1, 1].set_title('Score Change Rate (%)', fontsize=14, fontweight='bold')
axs[1, 1].set_xlabel('Date')
axs[1, 1].set_ylabel('Percentage Change')
axs[1, 1].grid(True, alpha=0.3, axis='y')
axs[1, 1].tick_params(axis='x', rotation=45)

# 调整布局
plt.tight_layout()

# 保存图表
complete_analysis_img = 'complete_score_analysis.png'
plt.savefig(complete_analysis_img, dpi=300, bbox_inches='tight')
plt.show()

print(f"完整成绩分析图已保存为 {complete_analysis_img}")

# 输出详细统计信息
print("\n" + "="*50)
print("COMPREHENSIVE SCORE ANALYSIS REPORT")
print("="*50)

print(f"\nBasic Statistics:")
print(f"  Mean Score:     {df['Score'].mean():.2f}")
print(f"  Median Score:   {df['Score'].median():.2f}")
print(f"  Max Score:      {df['Score'].max():.2f}")
print(f"  Min Score:      {df['Score'].min():.2f}")
print(f"  Std Deviation:  {df['Score'].std():.2f}")
print(f"  Score Range:    {df['Score'].max() - df['Score'].min():.2f}")

print(f"\nScore Categories:")
print(f"  Excellent (90+):     {len(df[df['Score'] >= 90])} scores")
print(f"  Good (80-89):        {len(df[(df['Score'] >= 80) & (df['Score'] < 90)])} scores")
print(f"  Average (70-79):     {len(df[(df['Score'] >= 70) & (df['Score'] < 80)])} scores")
print(f"  Below Average (<70): {len(df[df['Score'] < 70])} scores")

print(f"\nTrend Analysis:")
trend = "Upward" if df['Score'].iloc[-1] > df['Score'].iloc[0] else "Downward"
print(f"  Overall Trend: {trend}")
print(f"  Start Score:   {df['Score'].iloc[0]:.2f}")
print(f"  End Score:     {df['Score'].iloc[-1]:.2f}")
print(f"  Total Change:  {df['Score'].iloc[-1] - df['Score'].iloc[0]:.2f}")