基于嵌套循环结果绘制8个获救犬种子图的技术实现请求
为8个获救犬种批量绘制子图实现方案
原代码存在的问题
- 循环范围
range(7)未覆盖全部8个犬种,导致漏绘 - 直接用列表匹配
df.breed == rescued_dog_race无法正确获取单个犬种的获救率 null_outcomes未按犬种区分,所有模拟结果混杂,无法单独绘图
完整实现代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt # 设置随机种子确保结果可复现 np.random.seed(1) # 核心参数 rescued_pop = 8 # 种群整体获救率百分比 rescued_dog_race = ["rottweiler", "poodle", "pitbull", "chihuahua", "shihtzu", "whippet", "terrier", "greyhound"] # 存储模拟结果:按犬种分类 breed_simulations = {} # 种群整体模拟结果(仅需运行一次) pop_simulations = [] # 先执行种群整体模拟 for _ in range(1000): simulated_pop = np.random.choice(["yes", "no"], size=100, p=[rescued_pop/100, 1 - rescued_pop/100]) pop_simulations.append(np.sum(simulated_pop == "yes")) # 循环每个犬种执行模拟 for breed in rescued_dog_race: # 提取当前犬种的获救率 rescued_rate = float(df.loc[df.breed == breed, "rescued"].to_string(index=False)) # 存储当前犬种的1000次模拟结果 breed_results = [] for _ in range(1000): simulated = np.random.choice(["yes", "no"], size=100, p=[rescued_rate/100, 1 - rescued_rate/100]) breed_results.append(np.sum(simulated == "yes")) breed_simulations[breed] = breed_results # 创建2行4列的子图网格 fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(16, 8)) # 扁平化子图数组,方便循环遍历 axes = axes.flatten() # 逐个绘制犬种子图 for idx, breed in enumerate(rescued_dog_race): ax = axes[idx] # 绘制当前犬种的模拟分布直方图 ax.hist(breed_simulations[breed], bins=15, alpha=0.6, label=f"{breed} 模拟") # 绘制种群整体的模拟分布直方图 ax.hist(pop_simulations, bins=15, alpha=0.6, label="种群整体模拟") # 设置子图样式 ax.set_title(f"{breed} 获救数量模拟分布") ax.set_xlabel("获救数量") ax.set_ylabel("模拟次数") ax.legend() # 自动调整子图间距,避免标签重叠 plt.tight_layout() plt.show()
关键实现要点
- 用字典
breed_simulations按犬种存储模拟结果,彻底避免数据混杂 - 种群模拟仅执行一次,提升代码运行效率
- 通过
plt.subplots创建网格子图,配合flatten()简化循环逻辑 - 每个子图同时展示犬种自身与种群的模拟分布,保持与单犬种图的一致性
tight_layout()自动优化子图间距,解决标签重叠问题
内容的提问来源于stack exchange,提问作者Diastat
相关产品推荐
相关产品推荐

