【问题标题】:Why is the legend shown in a Seaborn JointGrid incorrect?为什么 Seaborn JointGrid 中显示的图例不正确?
【发布时间】:2020-08-05 01:34:44
【问题描述】:

我正在试验来自SeabornJointGrid。我使用.plot_joint() 绘制我的散点图,使用hue 参数进行分组着​​色。我已过滤我的数据集以仅包含 5 个组中的 2 个,以防止图中重叠过多。

绘制的点看起来是正确的,因为它们符合我对我选择的两组的期望。此外,我通过查看过滤后的数据框仔细检查了我的过滤。这也是正确的,因为它只包含我选择的两个组。

但是,随散点图自动绘制的图例不正确。它显示了 4 个组(不知道为什么不是 5 个),并且着色也不正确。对于 2 组,我希望只有红色和蓝色(Set1 调色板中的前 2 种颜色),但我的第 2 组使用Set1 调色板中的第 4 种颜色着色。

plt.rcParams['figure.figsize'] = (12, 4)
df_tmp = df[df.Kmeans_Clusters.isin([0, 3])].copy()

# initialize Joint Grid
grid = sns.JointGrid(data=df_tmp, x='MP', y='PTS')

# plot scatter (main plot)
grid = grid.plot_joint(sns.scatterplot, data=df_tmp, hue='Kmeans_Clusters',
                       palette='Set1')

# plot marginal distplot for cluster 0, X & Y
sns.distplot(df_tmp[df_tmp.Kmeans_Clusters == 0].MP, ax=grid.ax_marg_x,
             vertical=False, color='firebrick', label='Cluster0')
sns.distplot(df_tmp[df_tmp.Kmeans_Clusters == 0].PTS, ax=grid.ax_marg_y,
             vertical=True, color='firebrick', label='Cluster0')

# plot marginal distplot for cluster 3, X & Y
sns.distplot(df_tmp[df_tmp.Kmeans_Clusters == 3].MP, ax=grid.ax_marg_x,
             vertical=False, color='steelblue', label='Cluster3')
sns.distplot(df_tmp[df_tmp.Kmeans_Clusters == 3].PTS, ax=grid.ax_marg_y,
             vertical=True, color='steelblue', label='Cluster3')

plt.suptitle('PTS vs MP, Cluster 0 & 3\n1982-2019', y=1.05, fontsize=20)
plt.show()

jointgrid_incorrect_legend_and_coloring

--- 更新--- 我只是用一个简单的scatterplot(没有JointGrid)尝试了这个,我可以重复我之前的观察。 hue 参数和 scatterplot() 函数有什么我不理解的地方吗?

lmplot() 没有看到这个问题

plt.rcParams['figure.figsize'] = (12, 4)
df_tmp = df[df.Kmeans_Clusters.isin([0, 3])].copy()
sns.scatterplot(data=df_tmp, y='PTS', x='MP', hue='Kmeans_Clusters', palette='Set1')
plt.title('PTS vs MP\n1982-2019')
plt.xlabel('Minutes Played Annually')
plt.ylabel('Points Scored Annually')
plt.show()

【问题讨论】:

  • 一旦我意识到问题出在 scatterplot() 上,而不是我在更新 cmets 中提到的 JointGrid 上,我就能够微调我的 google 搜索。我最终使用的解决方法是将色调变量('Kmeans_Clusters')转换为字符串类型,并将其与非数字字符连接起来,这样它就不会以任何方式被解释为数字。如果我不这样做,我会得到一个属性错误。所以,最后,我的色调变量的类别现在是“cl_#”,而不是像以前那样只是#。图例现在只显示我过滤到的两个组以及我选择的调色板中正确的前 2 种颜色。

标签: python seaborn


【解决方案1】:

再次,一旦我微调了搜索,我就能找到解决方案。事实上,这里有另一个 stackoverflow 问题,它提出了同样的问题并得到了详细的回答:The `hue` parameter in Seaborn.relplot() skips an integer when given numerical data?

粘贴我使用的解决方案,如上面链接中所述:

""" 另一种方法是确保将值视为分类值。不幸的是,即使您将数字作为字符串插入,它们也会被转换为返回到上述相同机制的数字。这可能被视为一个错误。

但是,您可以选择使用真实的类别,例如单个字母。

'簇':list("ABCDE")

工作正常, """

【讨论】:

    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多