每次调用sns.relplot 等图形级函数时,都会创建一个新图形。 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()
目前还不清楚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]