根据数据点的数量在同一轴上绘制swarmplot或boxplot

时间:2018-06-27 07:25:16

标签: python matplotlib seaborn boxplot

我有一个包含几列的数据框,每列有5到2535个条目(其余为NAN)。我想在该列有9个以上的数字条目和一个swarmplot列时绘制一个箱形图。我用疯狂的绘画技巧创造了一个榜样。 enter image description here

问题是,我只能像this example一样将它们都绘制为覆盖图。我尝试使用position关键字,但这仅适用于boxplot,不适用于swarmplot。那么,该怎么办呢?

可以像这样生成示例数据集:

np.random.seed(1)
df = pd.DataFrame(np.nan, index=range(100), columns=range(11))
for i, column in enumerate(df.columns):
    if i % 2 == 0:
        fill_till = np.random.randint(1,11)
        df.loc[:fill_till-1,column] = np.random.random(fill_till)
    else:
        fill_till = np.random.randint(11,101)
        df.loc[:fill_till-1,column] = np.random.random(fill_till)

2 个答案:

答案 0 :(得分:5)

您可以创建数据框的两个副本,一个用于箱形图,一个用于群图。然后,在每个副本中,将不想以这种方式绘制的列 中的值设置为nan

col_mask = df.count() > 9
swarm_data = df.copy()
swarm_data.loc[:, col_mask] = np.nan
box_data = df.copy()
box_data.loc[:, ~col_mask] = np.nan

然后将每个复制的数据帧传递给适当的seaborn函数。

sns.swarmplot(data=swarm_data)
sns.boxplot(data=box_data)
plt.show()

在创建群体图时,seaborn将不会为填充nan的列绘制任何内容,但会留有空间。相反,箱形图将发生,从而保留了列顺序。

以上代码生成的图表如下所示:

enter image description here

这种方法也适用于带有非数字标签的列:

enter image description here

答案 1 :(得分:1)

要详细说明评论,这是一个基本示例(由于you do not provide a toy data set,很难构建一个可以反映您情况的示例)。

import numpy as np
from matplotlib import pyplot as plt
import pandas as pd

#column order
real_order = ["B", "D", "A", "E", "C"]
#first data set
x1 = ["A", "C", "B"]
y1 = [9,     3,   1]
#second dataset
x2 = ["D", "C", "E", "A"]
y2 = [2,    11,   4,   5]

#prepare the axis
plt.plot(real_order, np.repeat(np.nan, len(real_order)))
#fill in bars 
plt.bar(x1, y1, color = "r", label = "bars")
#fill in markers
plt.plot(x2, y2, "b*", label = "markers")
plt.legend()
plt.show()

输出:

enter image description here

相关问题