plot.py 3.63 KB
Newer Older
jerrrrry's avatar
jerrrrry committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import argparse, pandas as pd, matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt, re, os

def find_avg_row(df):
    for idx, row in df.iterrows():
        if any(isinstance(cell, str) and re.search(r'平均值|Average', str(cell)) for cell in row):
            return idx
    return df.index[-1]

def extract_values(df):
    idx = find_avg_row(df)
    vals = [float(v) for v in df.iloc[idx].dropna().iloc[-4:] if str(v).replace('.', '').isdigit()]
    if len(vals) != 4:
        vals = [float(v) for v in df.iloc[-1].dropna().iloc[-4:] if str(v).replace('.', '').isdigit()]
    if len(vals) != 4:
        raise ValueError("无法提取4个百分比")
    return {
        "Total_throughput": vals[3],
        "generate_throughput": vals[2],
        "singel_road_generate_throughput": vals[1],
        "generate_throughput_without_ttft": vals[0]
    }

def plot_summary(file_path, output_prefix):
    xls = pd.ExcelFile(file_path)
    summary = {}
    for sheet in xls.sheet_names:
        try:
            df = pd.read_excel(xls, sheet_name=sheet, header=None)
            summary[sheet] = extract_values(df)
        except Exception:
            continue
    if not summary:
        print("❌ 无数据可绘图")
        return

jerrrrry's avatar
jerrrrry committed
38
39
40
41
42
43
44
45
46
47
48
49
    labels = [
        "Total_throughput",
        "generate_throughput",
        "singel_road_generate_throughput",
        "generate_throughput_without_ttft"
    ]
    # 大师级配色(Material 2024)
    colors = ['#005F73', '#0A9396', '#94D2BD', '#E9D8A6']




jerrrrry's avatar
jerrrrry committed
50
51
52
53
    models = list(summary.keys())
    x = range(len(models))
    bar_width = 0.18

jerrrrry's avatar
jerrrrry committed
54
55
56
57
    fig, ax = plt.subplots(figsize=(max(len(models) * 1.1, 14), 8))
    fig.patch.set_facecolor('#F8F9FA')
    ax.set_facecolor('#FFFFFF')

jerrrrry's avatar
jerrrrry committed
58
59
60
    for i, lab in enumerate(labels):
        vals = [summary[m][lab] for m in models]
        offset = (i - 1.5) * bar_width
jerrrrry's avatar
jerrrrry committed
61
62
63
64
        bars = ax.bar([p + offset for p in x], vals, width=bar_width,
                      label=lab.replace('_', ' ').title(), color=colors[i])

        # 保持倾斜 60° + 虚线指引
jerrrrry's avatar
jerrrrry committed
65
66
        for bar, v in zip(bars, vals):
            height = bar.get_height()
jerrrrry's avatar
jerrrrry committed
67
68
69
70
71
72
73
74
75
76
77
            # 虚线起点(柱顶中心)
            line_start = (bar.get_x() + bar.get_width() / 2, height)
            # 文本终点(再向上 5%)
            text_pos   = (line_start[0], height + max(vals) * 0.05)
            # 画虚线
            ax.plot([line_start[0], text_pos[0]], [line_start[1], text_pos[1]],
                    color='#555555', linestyle='--', linewidth=0.8, alpha=0.7)
            # 倾斜 60° 文字
            ax.text(text_pos[0], text_pos[1], f"{v:.1f}%",
                    ha='center', va='bottom', fontsize=7,
                    rotation=60, color='#000000', weight='bold')
jerrrrry's avatar
jerrrrry committed
78

jerrrrry's avatar
jerrrrry committed
79
80
81
82
83
84
85
86
    # 轴 & 网格
    ax.set_xticks(x)
    ax.set_xticklabels(models, rotation=25, ha='right', fontsize=10, weight='bold')
    ax.set_ylabel("Percentage", fontsize=12, weight='bold')
    ax.set_title("Throughput Comparison", fontsize=16, weight='bold', pad=20)
    ax.grid(axis='y', linestyle='-', linewidth=0.3, alpha=0.3, color='#DEE2E6')
    ax.legend(frameon=False, loc='upper left', bbox_to_anchor=(1.02, 1), fontsize=9)
    plt.subplots_adjust(left=0.05, right=0.85, bottom=0.12, top=0.92)
jerrrrry's avatar
jerrrrry committed
87
88

    for ext in ['png', 'pdf']:
jerrrrry's avatar
jerrrrry committed
89
90
        plt.savefig(f"{output_prefix}.{ext}", dpi=300 if ext == 'png' else None,
                    bbox_inches='tight')
jerrrrry's avatar
jerrrrry committed
91
92
    print(f"✅ 已保存:{output_prefix}.png / .pdf")

jerrrrry's avatar
jerrrrry committed
93

jerrrrry's avatar
jerrrrry committed
94
95
96
97
98
99
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("xlsx_path")
    parser.add_argument("-o", "--output", default="summary_chart")
    args = parser.parse_args()
    plot_summary(args.xlsx_path, args.output)