gpt4 book ai didi

python - 如何避免 seaborn FacetGrid 中的空网格

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:25 28 4
gpt4 key购买 nike

我有一个个人特征数据框,例如学校成绩、年龄、体重和高度。我想调查这些数据在 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)

在此先感谢您的支持,基督徒

最佳答案

如果您只是为了演示目的而隐藏图表(但保留整体网格结构):

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

关于python - 如何避免 seaborn FacetGrid 中的空网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186545/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com