我们可以在生成带状图后通过循环轴刻度和刻度标签来限制每条中线到其各自列的宽度。这也使得代码能够独立于要绘制的样本(列)的数量进行操作。
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({"sample": ["X", "X", "X", "Y", "Y", "Y"],
"value": [0.2, 0.3, 0.4, 0.7, 0.75, 0.8],
"rep": ["a", "b", "c", "a", "b", "c"]})
ax = sns.stripplot(x="sample", y="value", data=df, palette="Set1", s=8)
# distance across the "X" or "Y" stipplot column to span, in this case 40%
median_width = 0.4
for tick, text in zip(ax.get_xticks(), ax.get_xticklabels()):
sample_name = text.get_text() # "X" or "Y"
# calculate the median value for all replicates of either X or Y
median_val = df[df['sample']==sample_name].value.median()
# plot horizontal lines across the column, centered on the tick
ax.plot([tick-median_width/2, tick+median_width/2], [median_val, median_val],
lw=4, color='k')
plt.show()
seaborn stripplot with median lines drawn: