import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import make_interp_spline

plt.rcParams['font.family'] = 'SimHei'  # 设置中文字体

# 数据
november = np.array([35.22, 10.41, 17.22, 10.70, 10.29, 18.66, 4.41, 6.24, 49.72, 47.70,
     36.55, 14.85, 19.46, 10.93, 40.26, 19.82, 19.49, 16.01, 99.32, 14.77,
     3.96, 10.49, 21.71, 13.06, 20.34, 0.77, 11.38, 3.66, 1.21, 2.31, 3.24])

cumulative = np.array([499.80, 161.37, 273.29, 134.79, 90.92, 348.99, 106.89, 196.44, 656.95, 580.70,
     518.10, 179.41, 250.16, 122.06, 552.74, 268.20, 221.43, 197.68, 1080.26, 160.60,
     39.51, 111.76, 290.87, 95.87, 183.62, 6.08, 133.50, 64.86, 18.30, 23.81, 103.81])

# 计算直方图
def histogram_with_counts(data, bins=10):
    counts, bin_edges = np.histogram(data, bins=bins)  # 计算直方图
    bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2  # 计算每个柱子的中心
    cumulative_counts = np.cumsum(counts)  # 计算累计频数
    return bin_edges, bin_centers, counts, cumulative_counts

# 计算基于直方图的累计计数
bins = 10  # 直方图的柱子个数
edges_nov, centers_nov, counts_nov, cumulative_counts_nov = histogram_with_counts(november, bins=bins)
edges_cum, centers_cum, counts_cum, cumulative_counts_cum = histogram_with_counts(cumulative, bins=bins)

# 创建两个子图
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# 11月消费累计频数柱状图
axes[0].bar(centers_nov, cumulative_counts_nov, width=(edges_nov[1] - edges_nov[0]) * 0.8, alpha=0.6, color='blue', label="累计频数")

# 拟合累计频数曲线
spl_nov = make_interp_spline(centers_nov, cumulative_counts_nov, k=3)  # 使用三次样条插值
x_new_nov = np.linspace(min(centers_nov), max(centers_nov), 1000)  # 增加插值点的数量
y_new_nov = spl_nov(x_new_nov)
axes[0].plot(x_new_nov, y_new_nov, color="red", linewidth=2, label="拟合累计曲线")

axes[0].set_ylabel("累计频数", fontsize=12)
axes[0].set_ylim(0, 35)  # 设置y轴上限为35

# 设置标题和图例
axes[0].set_title("11月消费累计频数分布", fontsize=14)
axes[0].set_xlabel("消费金额（元）", fontsize=12)
axes[0].grid(True)
axes[0].legend()

# 1-11月累计消费累计频数柱状图
axes[1].bar(centers_cum, cumulative_counts_cum, width=(edges_cum[1] - edges_cum[0]) * 0.8, alpha=0.6, color='green', label="累计频数")

# 拟合累计频数曲线
spl_cum = make_interp_spline(centers_cum, cumulative_counts_cum, k=3)  # 使用三次样条插值
x_new_cum = np.linspace(min(centers_cum), max(centers_cum), 1000)  # 增加插值点的数量
y_new_cum = spl_cum(x_new_cum)
axes[1].plot(x_new_cum, y_new_cum, color="red", linewidth=2, label="拟合累计曲线")

axes[1].set_ylabel("累计频数", fontsize=12)
axes[1].set_ylim(0, 35)  # 设置y轴上限为35

# 设置标题和图例
axes[1].set_title("1-11月累计消费累计频数分布", fontsize=14)
axes[1].set_xlabel("消费金额（元）", fontsize=12)
axes[1].grid(True)
axes[1].legend()

# 调整布局
plt.tight_layout()
plt.show()