从具有行和列多索引的数据框创建数据框箱线图。

3
我有一个Pandas数据框,我想创建一个按qdepth组织的“dur”值的箱形图,其中包括两个变量client和server(qdepth在x轴上,duration在y轴上)。看起来我需要将client和server作为列。尝试使用unstack和reset_index的组合仍然无法解决问题。请参考以下示例图片:example

如果您能以一种我们可以直接使用pd.read_clipboard()在pandas中导入的格式发布数据样本,那将会很有帮助(请在您的计算机上测试它)。此外,也许提供您想要获得的箱线图的草图会更有帮助。 - Julien Marrec
1个回答

4

由于您只提供了一张图片而没有发布数据,因此我重新创建了一些虚拟数据:

qdepth,mode,runid,dur
1,client,0x1b7bd6ef955979b6e4c109b47690c862,7.0
1,client,0x45654ba030787e511a7f0f0be2db21d1,30.0
1,server,0xb760550f302d824630f930e3487b4444,19.0
1,server,0x7a044242aec034c44e01f1f339610916,95.0
2,client,0x51c88822b28dfa006bf38603d74f9911,15.0
2,client,0xd5a9028fddf9a400fd8513edbdc58de0,49.0
2,server,0x3943710e587e3932adda1cad8eaf2aeb,30.0
2,server,0xd67650fd984a48f2070de426e0a942b0,93.0

加载数据:df = pd.read_clipboard(sep=',', index_col=[0,1,2])

选项 1:

df.unstack(level=1).boxplot()

enter image description here

选项2:

df.unstack(level=[0,1]).boxplot()

Option 2

选项 3:

使用 seaborn:

import seaborn as sns
sns.boxplot(x="qdepth", hue="mode", y="dur", data=df.reset_index(),)

enter image description here

更新:

为了回答您的评论,这里提供了一种使用 pandas 和 matplotlib 重新创建 seaborn 选项的非常近似的方法(可用作起点):

fig, ax = plt.subplots(nrows=1,ncols=1, figsize=(12,6))
#bp = df.unstack(level=[0,1])['dur'].boxplot(ax=ax, return_type='dict')

bp = df.reset_index().boxplot(column='dur',by=['qdepth','mode'], ax=ax, return_type='dict')['dur']

# Now fill the boxes with desired colors
boxColors = ['darkkhaki', 'royalblue']
numBoxes = len(bp['boxes'])
for i in range(numBoxes):
    box = bp['boxes'][i]
    boxX = []
    boxY = []
    for j in range(5):
        boxX.append(box.get_xdata()[j])
        boxY.append(box.get_ydata()[j])
    boxCoords = list(zip(boxX, boxY))
    # Alternate between Dark Khaki and Royal Blue
    k = i % 2
    boxPolygon = mpl.patches.Polygon(boxCoords, facecolor=boxColors[k])
    ax.add_patch(boxPolygon)

plt.show()

enter image description here


感谢您的回答。Seaborn中的“hue”参数似乎是我正在寻找的内容。如果没有Seaborn,有没有任何方法在vanilla Pandas中实现分组?虽然这不影响接受此答案。 - Noah Watkins
Seaborn 实际上就像 pandas 一样使用了原始的 matplotlib,所以是有方法的。你可以查看 Seaborn 的源代码(从这里开始),还可以参考这个 matplotlib 示例,展示了如何给盒子着色。 (PS:除了接受答案外,点赞也是不错的选择) - Julien Marrec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接