gpt4 book ai didi

python - 将箱线图与 stripplot 叠加的问题

转载 作者:行者123 更新时间:2023-12-05 02:27:50 25 4
gpt4 key购买 nike

我使用以下代码用带状图覆盖箱线图:

# create a color palette
palette = ['tab:blue', 'tab:orange', 'tab:red',]

# plot the data
plt.figure(figsize = (18,8))
sns.stripplot(data = int_genes_melt, y = 'value', x = 'Genes', color = 'black')
sns.boxplot(data = int_genes_melt, y = 'value', x = 'Genes', hue = 'pulldown', hue_order= ['BT474', 'both', 'SKBR3'], palette = palette)
plt.ylabel('relative protein abundance to control')
plt.xticks(rotation=40)
sns.despine()

输出看起来像这样:

enter image description here

如您所见,条状图中的一些数据点与箱线图(箱线图橙色)完美重叠。然而,左边的第一个红色箱线图似乎并没有很好地与带状图重叠。为什么会发生这种情况有什么建议吗?

最佳答案

为什么会得到这个输出

这是因为 int_genes_melt 中并非所有类型的 'Genes' 都具有这三种类型(['BT474', 'both', 'SKBR3' ]) 的 'pulldown'

'Genes'的第一个类别(图中的第一个框和相关点)为例。只有一个红框,表示第一类中所有数据点的'pulldown'属性为'SKBR3'('SKBR3' 根据 hue_order 着色为 'tab:red'

  1. 箱线图行为。表示 'BT474''both' 的框丢失了。这是因为第一类中没有这样的数据具有这两种'pulldown'。因此,只有属于 'Genes' 第一类的三个框的最后一个被绘制。

  2. stripplot行为,第一类的点绘制在中心,关于'both'的第二个方框所在的位置,就在方框的左边'SKBR3'

所以你可以看到在第一类中,点位于框的左侧。再举一个例子,在第五类中,然而,所有数据都有 'both' 作为它们的 'pulldown' 属性,所以绘制了三个框的第二个框,只是与带状图对齐。

可以引用the document of boxplot ,在页面搜索“Draw a boxplot with nested grouping when some bins are empty”,你可以找到一个说明箱线图这种行为的官方例子。

如何修复

您可以添加hue='pulldown' 属性并设置dodge=True。这样,每个类别的stripplot也会根据pulldown属性分成三个 strip 。

可以引用the document of stripplot你会发现你可以“在主要分类轴上的不同位置绘制色调变量的每个级别”。

以下是代码示例:

没有这个 hue=dodge=True:

import seaborn as sns
import matplotlib.pyplot as plt
palette = ['tab:blue', 'tab:orange']
tips = sns.load_dataset("tips")
sns.stripplot(data=tips, y='total_bill', x='day', color='black')
sns.boxplot(data=tips, x="day", y="total_bill", hue="time", hue_order=['Lunch', 'Dinner'], palette=palette)
sns.despine()
plt.show()

其中给出(注意箱线图和条状图没有对齐,第三和第四列就像你的情况):

enter image description here修复后:

import seaborn as sns
import matplotlib.pyplot as plt
palette = ['tab:blue', 'tab:orange']
tips = sns.load_dataset("tips")
sns.stripplot(data=tips, y='total_bill', x='day', hue="time", dodge=True, color='black')
sns.boxplot(data=tips, x="day", y="total_bill", hue="time", hue_order=['Lunch', 'Dinner'], palette=palette)
sns.despine()
plt.show()

给出: enter image description here

至于您的代码,我认为您应该使用(正如@Michael 指出的那样):

sns.stripplot(data=int_genes_melt, y='value', x='Genes', hue='pulldown', hue_order=['BT474', 'both', 'SKBR3'],  dodge=True, color='black')

您也可以关闭引用 this link 的图例如果你愿意的话。

关于python - 将箱线图与 stripplot 叠加的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72887125/

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