2
我有一个像学校成绩,年龄,体重和身高的个人特征的数据框。 我想调查一个seaborn Facetgrid
内的这些数据的密度分布。如何避免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 |
+-------+------------+------------+-------+-----------------------+
..............................................................
+=======+============+============+=======+=======================+
这个数字看起来是这样的:
正如你可以看到,有很多空的地块,我想重新排列只有带有数据的网格的情节。在列应显示具有相同的网格type
。一个例子(用Paint创建)可以在下面看到。 此外,x轴对于所有列均等比例缩放。我如何单独调整x轴(甚至可能是对数)。
rearranged figure (with Paint)
预先感谢您的支持, 基督教
“*作为你可以看到很多我想摆脱的情节情节*“这是什么意思?轴被移除后是否应该有空白部分?应该只将具有数据的轴重新排列成紧凑的网格?你需要具体并告诉使用什么*真正*想要的。 –
*“我如何单独调整x轴(甚至可能是对数)”*您已经在y轴上通过'sharey = False'参数来执行此操作。用'sharex'做同样的事情。要将x轴设置为对数刻度,可以使用'grid_ts.set(xscale ='log')。但是,我不建议这样做。如果您的数据是对数正态分布的,那么您应该在数据的日志中计算KDE。 –
@PaulH感谢您的问题。 1)_“是否只有带数据的轴被重新排列成一个紧凑的网格?” - 是的,这正是我想要的 – ChristianH