用多个子地块在seaborn散点图上覆盖垂直线

2024-06-11 13:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个散点图,由使用seaborn的“col”和“row”功能的多个子图组成,例如

sns.relplot(data=data,x="YEL-HLog",y="FSC-HLog",hue="Treatment",row="Fraction",col="Biounit",s=1)

我想在每个子地块的参数x上覆盖一条线。更重要的是,对于不同的列,行是不同的。在这方面,我使用了以下代码:

sns.relplot(data=new,x="Threshold",y="FSC-HLog",hue="Treatment",row="Fraction",col="Biounit",s=1)

“New”是相同的数据帧,但插入了“Threshold”列。所以除了x值之外,所有的东西都是一样的

然而,这只是给了我两个不同的图表。如何将两者结合在一起在同一个情节上显示


Tags: 功能datathresholdcolseabornhuerowsns
1条回答
网友
1楼 · 发布于 2024-06-11 13:12:31

每次调用^{}之类的地物级别函数时,都会创建一个新地物relplot返回一个FacetGrid,其中包含如何创建子批的信息。您可以在g.axes之间循环,并在每一条上画一条线

以下是一个例子:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

N = 2000
data = pd.DataFrame({"YEL-HLog": np.random.rand(N),
                     "FSC-HLog": np.random.rand(N),
                     "Treatment": np.random.choice(['A', 'B', 'C'], N),
                     "Fraction": np.random.choice(['Fr1', 'Fr2'], N),
                     "Biounit": np.random.choice(['Unit1', 'Unit2', 'Unit3'], N)})
threshold_dict = {('Fr1', 'Unit1'): 0.1, ('Fr1', 'Unit2'): 0.2, ('Fr1', 'Unit3'): 0.3,
                  ('Fr2', 'Unit1'): 0.6, ('Fr2', 'Unit2'): 0.7, ('Fr2', 'Unit3'): 0.8}

g = sns.relplot(data=data, x="YEL-HLog", y="FSC-HLog", hue="Treatment", row="Fraction", col="Biounit", height=3)
for row, row_name in enumerate(g.row_names):
    for col, col_name in enumerate(g.col_names):
        ax = g.axes[row, col]
        threshold = threshold_dict[(row_name, col_name)]
        ax.axvline(threshold, color='red', ls=' ', lw=3)
g.fig.subplots_adjust(left=0.07, bottom=0.09)
plt.show()

sns.relplot with vertical line

目前还不清楚new数据帧是如何获得其值的。它可以从threshold_dict创建,但这似乎是一个不必要的间接过程。为了完整起见,在这种情况下,代码可以如下所示:

new_df = data
new_df["Threshold"] = data.apply(lambda d: threshold_dict[(d['Fraction'], d['Biounit'])], axis=1)
for ...
   for ...
        threshold = new_df[(new_df["Fraction"] == row_name) & (new_df["Biounit"] == col_name)]["Threshold"].iloc[0]

相关问题 更多 >