import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from acycle.util.utiltool import readTxt
def plot_distribution_with_stats(file = None,ax=None):
    if file:
        x,y = readTxt(file)
    elif data:
        x,y = data
    else:
        # 生成示例数据（替换为您的实际数据）
        data = np.random.normal(loc=0, scale=1, size=1000)

    # 创建图形和主坐标轴
    fig, ax1 = plt.subplots(figsize=(10, 6))

    # --- 绘制柱状图 ---
    # 自动计算合适的bin数量
    bin_width = 0.5
    bins = np.arange(min(data), max(data) + bin_width, bin_width)

    # 绘制柱状图（使用左y轴）
    n, bins, patches = ax1.hist(data, bins=bins, 
                            color='skyblue', 
                            edgecolor='white',
                            alpha=0.7,
                            label='Histogram')

    # --- 绘制平滑曲线(KDE) ---
    # 创建第二个y轴（共享x轴）
    ax2 = ax1.twinx()

    # 计算核密度估计
    kde = gaussian_kde(data)
    x_grid = np.linspace(min(data)-1, max(data)+1, 500)
    y_kde = kde(x_grid)

    # 绘制KDE曲线（使用右y轴）
    ax2.plot(x_grid, y_kde, 'r-', linewidth=2, label='KDE Smooth Curve')

    # --- 图形美化 ---
    # 设置标题和坐标轴标签
    ax1.set_title('Histogram with KDE Smooth Curve', pad=20)
    ax1.set_xlabel('Value')
    ax1.set_ylabel('Frequency (Histogram)', color='skyblue')
    ax2.set_ylabel('Density (KDE)', color='red')

    # 设置坐标轴颜色匹配
    ax1.tick_params(axis='y', colors='skyblue')
    ax2.tick_params(axis='y', colors='red')

    # 添加网格线
    ax1.grid(axis='y', alpha=0.3)

    # 组合图例
    lines1, labels1 = ax1.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper right')

    plt.tight_layout()
    plt.show()