gpt4 book ai didi

python - 使用 stripplot 在 seaborn 中绘制带有中线的点

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:15 26 4
gpt4 key购买 nike

我在 seaborn 中有以下情节:

df = pandas.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"]})
plt.figure()
ax = sns.stripplot(x="sample", y="value", edgecolor="none",
hue="sample", palette="Set1", data=df)

# how to plot median line?
plt.show()

它以灰度颜色绘制点,而不是使用 Set1,并且在图例中只显示 X 而不是 Y:

s

我还想在 XY 的中间添加一条水平线。如何才能做到这一点? factorplot 似乎没有水平线选项。

最佳答案

我们可以在生成 strip 图后循环遍历坐标轴刻度和刻度标签,从而将每条中线的宽度限制在其各自的列中。这也使代码能够独立于要绘制的样本(列)数量运行。


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: seaborn stripplot with median lines drawn

关于python - 使用 stripplot 在 seaborn 中绘制带有中线的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37619952/

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