# -*- coding: utf-8 -*-
"""图 7-8　散点图示例 —— 教材第 156 页

按「图内要素」逐项还原：
· 只有左纵轴与下横轴两条轴线，无边框、无刻度线、无刻度数字
· 纵轴左侧竖排文字「程序员的水平」，横轴下方「每个模块差错数」
· 约 35 个黑色实心圆点，沿自左上向右下的斜带散布；点排成多排，相邻排横向错开约半个点距
· 一条黑色实线（回归线）自左上向右下贯穿点群，两端略超出点群，表示负相关

说明：原图无刻度与数值，点位按教材照片逐点数字化（共 33 点，原描述为「约 35 个」）；
回归线由这组点最小二乘拟合，仅示意「每个模块差错数」与「程序员的水平」的负相关走向。
"""
import os
import sys

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, save, INK, NAV

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图7-8-散点图示例.png')

# 由教材照片逐点数字化（0–100 相对坐标，y 向上）
PTS = [
    (14.2, 90.7), (19.0, 90.7), (4.3, 90.2), (11.8, 80.2),
    (16.7, 80.5), (24.0, 80.7), (29.0, 80.7), (2.0, 69.8),
    (6.9, 69.0), (21.7, 70.5), (26.5, 70.7), (9.5, 60.2),
    (34.0, 60.7), (38.9, 61.0), (31.7, 50.5), (36.5, 50.7),
    (43.9, 50.7), (48.8, 51.0), (41.5, 40.5), (46.4, 40.7),
    (53.8, 40.7), (58.7, 41.0), (51.4, 30.5), (56.2, 30.5),
    (63.6, 30.7), (68.6, 31.0), (61.2, 20.2), (66.1, 20.5),
    (73.5, 20.5), (78.7, 20.7), (71.1, 10.5), (76.1, 10.5),
    (81.2, 10.7),
]


def pin(ax):
    """钉住数据范围，防止 _draw.save() 的画布自适应扩展压扁图表。"""
    x0, x1 = ax.get_xlim()
    y0, y1 = ax.get_ylim()
    ax.dataLim.set(Bbox.from_extents(x0, y0, x1, y1))
    ax.set_autoscale_on(False)


def main():
    setup()
    xs = np.array([p[0] for p in PTS])
    ys = np.array([p[1] for p in PTS])

    fig, ax = plt.subplots(figsize=(9.0, 6.2))
    ax.plot(xs, ys, linestyle='none', marker='o', ms=6.0,
            markerfacecolor=INK, markeredgecolor=INK, zorder=3)

    # 最小二乘回归线：两端略超出点群
    k, b = np.polyfit(xs, ys, 1)
    lx = np.array([-1.0, 88.5])
    ax.plot(lx, k * lx + b, color=INK, lw=1.5, zorder=2)

    ax.set_xlim(-2.0, 99.0)
    ax.set_ylim(-2.0, 99.0)
    ax.set_box_aspect(0.5)          # 保持教材原图 2:1 的绘图区比例
    ax.set_xticks([])
    ax.set_yticks([])

    for s in ('top', 'right'):
        ax.spines[s].set_visible(False)
    for s in ('left', 'bottom'):
        ax.spines[s].set_color(INK)
        ax.spines[s].set_linewidth(1.4)

    ax.set_ylabel('程序员的水平', fontsize=13, color=NAV, labelpad=10)
    ax.set_xlabel('每个模块差错数', fontsize=13, color=NAV, labelpad=10)

    pin(ax)
    save(fig, OUT)


if __name__ == '__main__':
    main()
