【问题标题】:Change marker style by a dataframe column (categorical) in seaborn stripplot通过 seaborn stripplot 中的数据框列(分类)更改标记样式
【发布时间】:2021-12-22 12:18:47
【问题描述】:

我希望将分类变量可视化为 seaborn stripplot 中的标记样式,但这似乎并不容易。是否有捷径可寻。例如,我正在尝试运行此代码

tips = sns.load_dataset("tips")
sns.stripplot(x="day", y="total_bill", hue="time", style="sex", jitter=True, data=tips)

失败了。另一种方法是使用 relplot,它确实提供了选项,但无法插入 jitter,这会降低可视化效果。

sns.relplot(x="day", y="total_bill", hue="time", data=tips, style="sex")

提供这个的作品

有没有什么方法可以使用 stripplot/catplot/swarmplot 做到这一点?

编辑:This 问题是相关的。然而,那里的解决方案似乎不允许生成大小图例(并且已经过时了)。

【问题讨论】:

标签: python matplotlib jupyter-notebook seaborn jupyter


【解决方案1】:

sns.relplot 是一个图形级函数,它依赖于轴级函数sns.scatterplotsns.scatterplot 有一个参数 x_jitter 不幸的是目前没有效果(seaborn 0.11.2)。

您可以通过掌握点的位置来模拟功能,添加一些随机抖动并重新分配这些位置。

这是一个例子:

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

tips = sns.load_dataset("tips")
ax = sns.scatterplot(x="day", y="total_bill", hue="time", data=tips, style="sex")
for points in ax.collections:
    vertices = points.get_offsets().data
    if len(vertices) > 0:
        vertices[:, 0] += np.random.uniform(-0.3, 0.3, vertices.shape[0])
        points.set_offsets(vertices)
xticks = ax.get_xticks()
ax.set_xlim(xticks[0] - 0.5, xticks[-1] + 0.5) # the limits need to be moved to show all the jittered dots
sns.move_legend(ax, bbox_to_anchor=(1.01, 1.02), loc='upper left')  # needs seaborn 0.11.2
sns.despine()
plt.tight_layout()
plt.show()

使用sns.relplot,您可以遍历所有子图:

g = sns.relplot(x="day", y="total_bill", hue="time", data=tips, style="sex")
for ax in g.axes.flat:
    for points in ax.collections:
        vertices = points.get_offsets().data
        if len(vertices) > 0:
            vertices[:, 0] += np.random.uniform(-0.3, 0.3, vertices.shape[0])
            points.set_offsets(vertices)
    xticks = ax.get_xticks()
    ax.set_xlim(xticks[0] - 0.5, xticks[-1] + 0.5) # the limits need to be moved to show all the jittered dots
plt.show()

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2016-10-22
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2019-07-27
    • 2019-08-01
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多