首页 > 解决方案 > 在一张图中从统计数据创建多个箱线图

问题描述

我无法找到一种解决方案,将根据统计数据创建的多个箱线图绘制到一个图表中。

从另一个应用程序中,我得到一个 Dataframe,其中包含绘制箱线图所需的不同指标(中位数、分位数 1,...)。虽然我可以使用以下代码从这些统计数据中绘制一个箱线图:

data = pd.read_excel("data.xlsx")

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)

row = data.iloc[:, 0]

stats = [{
        "label": i,  # not required
        "mean":  row["sharpeRatio"],  # not required
        "med": row["sharpeRatio_med"],
        "q1": row["sharpeRatio_q1"],
        "q3": row["sharpeRatio_q3"],
        # "cilo": 5.3 # not required
        # "cihi": 5.7 # not required
        "whislo": row["sharpeRatio_min"],  # required
        "whishi": row["sharpeRatio_max"],  # required
        "fliers": []  # required if showfliers=True
        }]

axes.bxp(stats)

plt.show()

我正在努力创建一个包含数据框中所有行的箱线图的图表。您知道如何实现这一目标吗?

标签: pythonmatplotlib

解决方案


您可以将字典列表传递给该bxp方法。从现有代码中获取此类列表的最简单方法是将字典构造放在一个函数中,并为数据帧的每一行调用它。

请注意,这data.iloc[:, 0]将是第一列,而不是第一行。

import matplotlib.pyplot as plt
import pandas as pd


def stats(row):
    return {"med": row["sharpeRatio_med"],
            "q1": row["sharpeRatio_q1"],
            "q3": row["sharpeRatio_q3"],
            "whislo": row["sharpeRatio_min"],  
            "whishi": row["sharpeRatio_max"]}


data = pd.DataFrame({"sharpeRatio_med": [3, 4, 2],
                     "sharpeRatio_q1": [2, 3, 1],
                     "sharpeRatio_q3": [4, 5, 3],
                     "sharpeRatio_min": [1, 1, 0],  
                     "sharpeRatio_max": [5, 6, 4]})

fig, axes = plt.subplots()
axes.bxp([stats(data.iloc[i, :]) for i in range(len(data))],
         showfliers=False)
plt.show()

三个箱线图


推荐阅读