python - 在一张图中从统计数据创建多个箱线图
问题描述
我无法找到一种解决方案,将根据统计数据创建的多个箱线图绘制到一个图表中。
从另一个应用程序中,我得到一个 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()
我正在努力创建一个包含数据框中所有行的箱线图的图表。您知道如何实现这一目标吗?
解决方案
您可以将字典列表传递给该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()
推荐阅读
- jpa-2.1 - 如何证明 JPA Enity 不能是 Hibernate 5 的最终类
- ios - 支持 ButtonStyle 中的不同形状
- c# - 如何从 azure http 函数中捕获 OAUTH2 clientapp
- python-3.x - 如何找到数据框所有行的局部最大值?
- excel - How to sort out discrete cells on the cell text color
- node.js - 以编程方式在不和谐上流式传输视频?
- r - 如何在函数调用中使用 data.table?
- arrays - Gson我无法反序列化包含纬度和经度的数组
- python - 从多个列表和列表列表中获取唯一对象。然后使用所有列表中的唯一对象创建一个新列表
- laravel - Laravel:从 Api (URL) 获取大数据