将 seaborn 的 catplot 与单轴一起使用,但仍指定色调

Using seaborn's catplot with a single axis, but still specify hue

我正在尝试将 swarmplot 与单轴一起使用,但数据点的颜色因类别而异。

这是一个例子:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
    
data = [
    (12, 50, 'Free', 'W'),
    (14, 1650, 'Free', 'W'),
    (17, 500, 'Free', 'W'),
    (17, 200, 'Free', 'W'),
    (28, 100, 'Free', 'W'),
    (33, 400, 'IM', 'W'),
    (36, 200, 'Fly', 'W'),
    (48, 100, 'Fly', 'W'),
    (52, 200, 'IM', 'W'),
    (54, 200, 'Back', 'W'),
    (54, 200, 'Breast', 'W'),
    (100, 100, 'Breast', 'W'),
    (100, 100, 'Back', 'W')
]


rank, dist, stroke, gender = zip(*data)
frame = pd.DataFrame(data={'rank': rank, 'distance': dist,
    'stroke': stroke, 'gender': gender})

# this one works, except I don't want to spread the points out
# along the y-axis
# sns.catplot(x='rank', y='distance', hue='stroke', kind='swarm', data=frame)

sns.catplot(x='rank', kind='swarm', data=frame, hue='stroke')
plt.show()

以上失败:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    sns.catplot(x='rank', kind='swarm', data=frame, hue='stroke')
  File "<...>/python3.6/site-packages/seaborn/categorical.py", line 3765, in catplot
    hue_order = list(map(utils.to_utf8, hue_order))
TypeError: 'NoneType' object is not iterable

有没有办法在不提供 y 字段的情况下让它工作?

hue= 必须嵌套在 x/y 下,因此您不能在没有提供的情况下使用它。

在我看来,显示数据的正确方法是使用 y='stroke'

sns.catplot(x='rank', y='stroke', kind='swarm', data=frame)

如果您真的希望所有点都在一条线上对齐,那么您可以伪造一个公共类别以用于所有点并将其传递给 y=。之后,获得合适的标签只是化妆品的问题:

frame.loc[:,'dummy'] = 'dummy'

g = sns.catplot(x='rank', y='dummy', hue='stroke', kind='swarm', data=frame)
g.axes[0,0].set_ylabel("")
g.axes[0,0].set_yticklabels([""])

由于不想显示y轴,可以用sns.countplot()代替sns.catplot()