# paint/pair_plot.py
import matplotlib.pyplot as plt
import numpy as np


def pair_plot(data=None, labels=None, title="Pair Plot",
              color_by=None, cmap='Set1', diag_kind='hist',
              markers='o', alpha=0.6):
    """
    绘制成对图（散点图矩阵）

    参数:
    data: 数据数组 (n_samples, n_features)
    labels: 特征名称
    title: 图表标题
    color_by: 按此列着色
    cmap: 颜色映射
    diag_kind: 对角线图形类型 ('hist' 或 'kde')
    markers: 标记样式
    alpha: 透明度
    """
    try:
        import pandas as pd
    except ImportError:
        print("请先安装 pandas: pip install pandas")
        return None

    # 生成默认数据
    if data is None:
        np.random.seed(42)
        n_samples = 100
        n_features = 4
        data = np.random.randn(n_samples, n_features)
        labels = [f'Feature {i + 1}' for i in range(n_features)]

    # 转换为DataFrame
    df = pd.DataFrame(data, columns=labels)

    # 创建成对图
    try:
        import seaborn as sns
        # 设置样式
        sns.set(style="whitegrid")

        # 创建成对图
        g = sns.pairplot(df,
                         hue=color_by,
                         diag_kind=diag_kind,
                         markers=markers,
                         palette=cmap,
                         plot_kws={'alpha': alpha})

        # 设置标题
        g.fig.suptitle(title, fontsize=16, fontweight='bold', y=1.02)

        plt.tight_layout()
        return g.fig, g
    except ImportError:
        print("请先安装 seaborn: pip install seaborn")

        # 使用matplotlib创建简化版本
        n_features = data.shape[1]
        fig, axes = plt.subplots(n_features, n_features,
                                 figsize=(3 * n_features, 3 * n_features))

        for i in range(n_features):
            for j in range(n_features):
                ax = axes[i, j]

                if i == j:
                    # 对角线：直方图
                    ax.hist(data[:, i], bins=20, alpha=0.7)
                    ax.set_title(labels[i] if labels else f'Feature {i + 1}')
                else:
                    # 非对角线：散点图
                    ax.scatter(data[:, j], data[:, i], alpha=alpha)

                # 设置标签
                if i == n_features - 1:
                    ax.set_xlabel(labels[j] if labels else f'Feature {j + 1}')
                if j == 0:
                    ax.set_ylabel(labels[i] if labels else f'Feature {i + 1}')

        fig.suptitle(title, fontsize=16, fontweight='bold')
        plt.tight_layout()
        return fig, axes