如何基于中位数、标准差、四分位数绘制箱线图?
基于预计算统计值绘制自定义箱线图
你可以直接用matplotlib手动构建所需的箱线图元素,无需依赖原始数据集。以下是针对你提供的统计值的实现方案:
给定统计值
median = 3637 std = 1274.997414 perc_25 = 2627.0 perc_75 = 4238.0
实现代码
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle # 初始化画布与坐标轴 fig, ax = plt.subplots(figsize=(6, 4)) # 设定箱体位置与宽度 box_width = 0.4 x_position = 1 # 绘制25/75分位数界定的箱体 box = Rectangle( (x_position - box_width/2, perc_25), box_width, perc_75 - perc_25, fill=False, edgecolor='black', linewidth=1.5 ) ax.add_patch(box) # 绘制中位数线 ax.hlines( median, x_position - box_width/2, x_position + box_width/2, color='black', linewidth=2 ) # 计算中位数±标准差的点坐标 std_low = median - std std_high = median + std # 绘制两侧标准差对应点 ax.scatter( [x_position, x_position], [std_low, std_high], color='red', zorder=5 ) # 调整坐标轴显示 ax.set_ylim(std_low - 200, std_high + 200) ax.set_xlim(0.5, 1.5) ax.set_xticks([x_position]) ax.set_xticklabels(['自定义箱线图']) ax.set_ylabel('数值') plt.title('基于预计算统计值的箱线图') plt.show()
代码说明
- 箱体:通过
Rectangle绘制,上下边界对应25分位数和75分位数,宽度固定以保证可视化效果 - 中位数线:用
hlines绘制在箱体中间,贯穿箱体宽度以突出中位数位置 - 标准差点:计算
median ± std后,用scatter标记在箱体正上下方,红色点便于区分 - 坐标轴范围可根据实际需求调整,确保所有元素完整展示
内容的提问来源于stack exchange,提问作者Jonas Apelt
相关产品推荐
相关产品推荐

