如何避免seaborn FacetGrid中的空网格

时间:2016-10-21 22:59:38

标签: python seaborn facet-grid

我有个人特征的数据框,如学校成绩,年龄,体重和身高。 我想调查这些数据在seaborn Facetgrid中的密度分布。

import pandas as pd
import seaborn as sns
import random
import matplotlib.pyplot as plt

# creation of artifical data
random.seed = 10
high = [random.uniform(3.0,6.0) for i in range(50)]
uni = [random.uniform(1.0, 4.0) for i in range(50)]
math = [random.uniform(1.0, 6.0) for i in range(50)]
bio = [random.uniform(1.0, 6.0) for i in range(50)]
history = [random.uniform(1.0, 6.0) for i in range(50)]
age = [random.randint(15,45) for i in range(50)]
height = [random.randint(150,210) for i in range(50)]
weight = [random.randint(50,100) for i in range(50)]

df = pd.DataFrame()
df["value"] = high + uni + math + bio + history + age + height + weight
df["type"] = 100*["final_exam"] + 150*["grade"] + 150*["body"]
df["id"] = 50*["highschool"] + 50*["university"] + 50*["math"] + 50*["bio"]    + 50*["history"] + 50*["age"] + 50*["heigt"] + 50*["weight"]
df["group"] = "A"
df = df[["group", "id", "type", "value"]]
df["para"] =df[["type", "id"]].apply(lambda x: "_".join(x), axis=1)


# Plotting function
def plot_poll(df, **kwargs):

    def plot_densitiy_distribution(data, **kwargs):
        sns.kdeplot(data["value"], shade=True)

    grid_ts = sns.FacetGrid(df, sharey=False, legend_out=True,    hue="group",col="type", row="id")
    grid_ts = grid_ts.map_dataframe(plot_densitiy_distribution)
    plt.tight_layout()
    plt.show()

# main
plot_poll(df)   

对于一个人来说,数据框看起来像这样,但总共50个 人员接受了采访:

+=======+============+============+=======+=======================+  
| group |     id     |    type    | value |          para         |
+=======+============+============+=======+=======================+   
|   A   | highschool | final_exam |  2.7  | final_exam_highschool |
+-------+------------+------------+-------+-----------------------+
|   A   | university | final_exam |  2.0  | final_exam_university |
+-------+------------+------------+-------+-----------------------+
|   A   |    math    |    grade   |  3.3  |     grade_math        |
+-------+------------+------------+-------+-----------------------+
   ..............................................................
+-------+------------+------------+-------+-----------------------+
|   A   |    age     |    body    |  27   |        body_age       |
+-------+------------+------------+-------+-----------------------+
   ..............................................................
+=======+============+============+=======+=======================+

该图如下所示:

enter image description here

正如你所看到的,有很多空图,我想重新排列只有数据网格存在的情节。在列中,应显示具有相同type的网格。一个例子(使用Paint创建)可以在下面看到。 此外,x轴对所有列均等缩放。如何单独缩放x轴(甚至可能是对数)。

rearranged figure (with Paint)

提前感谢您的支持, 基督教

1 个答案:

答案 0 :(得分:4)

如果您只想隐藏绘图用于演示目的(但保留整体网格结构):

    for (i,j,k), data in fg.facet_data():
        if data.empty:
            ax = fg.facet_axis(i, j)
            ax.set_axis_off()