# -*- coding: utf-8 -*-
"""图 7-5　直方图示例 —— 教材第 154 页

按「图内要素」逐项还原：
· 标题居中「未及时提交代码的原因」；左上角图例「● 次数」
· 纵轴无轴标题，刻度 0/5/10/15/20/25/30，各刻度画水平虚线，仅 0 处为实线基线
· 横轴无轴标题，五个类别：代码修复、团队协作、需求变更、设备故障、代码审查延迟
· 柱高：22、8、30（最高，顶到 30 网格线）、3（最矮）、16；原图不加数据标签
"""
import os
import sys

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

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

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图7-5-直方图示例.png')

CATS = ['代码修复', '团队协作', '需求变更', '设备故障', '代码审查延迟']
VALS = [22, 8, 30, 3, 16]


def main():
    setup()
    fig, ax = plt.subplots(figsize=(9.0, 5.9))

    x = range(len(CATS))
    ax.bar(x, VALS, width=0.46, color=FILL, edgecolor=ACC, linewidth=1.2, zorder=3)

    # 纵轴：0 处实线基线，其余刻度虚线网格
    ax.set_ylim(0, 32.5)
    ax.set_yticks([0, 5, 10, 15, 20, 25, 30])
    ax.grid(axis='y', color='#4a5568', linestyle=(0, (5, 3)), linewidth=0.8, zorder=1)
    ax.set_axisbelow(True)

    ax.set_xticks(list(x))
    ax.set_xticklabels(CATS, fontsize=12.5, color=INK)
    ax.tick_params(axis='y', labelsize=12, colors=INK, length=4, width=1.0)
    ax.tick_params(axis='x', length=0, pad=8)

    # 仅保留左、下轴脊；0 处即下轴脊，加粗为基线
    for s in ('top', 'right'):
        ax.spines[s].set_visible(False)
    ax.spines['left'].set_color(INK)
    ax.spines['left'].set_linewidth(1.1)
    ax.spines['bottom'].set_color(INK)
    ax.spines['bottom'].set_linewidth(1.4)

    ax.set_title('未及时提交代码的原因', fontsize=14.5, color=NAV, pad=14)

    handle = Line2D([], [], linestyle='none', marker='o', markersize=7.5,
                    markerfacecolor=INK, markeredgecolor=INK, label='次数')
    leg = ax.legend(handles=[handle], loc='upper left', fontsize=12,
                    frameon=False, handletextpad=0.5, borderpad=0.2,
                    bbox_to_anchor=(0.0, 1.02))
    for t in leg.get_texts():
        t.set_color(INK)

    ax.margins(x=0.06)
    fig.tight_layout()
    save(fig, OUT)


if __name__ == '__main__':
    main()
