使用Seaborn的Catplot与单轴,但仍指定色相

时间:2019-06-30 21:25:30

标签: python-3.x seaborn

我正在尝试将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字段的情况下使它正常工作?

2 个答案:

答案 0 :(得分:2)

hue=必须嵌套在x / y下,因此您不能在未同时提供两者的情况下使用它。

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

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

enter image description here

如果您真的希望所有点都对齐在一条直线上,则可以伪造一个用于所有点的通用类别,并将其传递给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([""])

enter image description here

答案 1 :(得分:0)

由于您不希望显示y轴,因此可以使用sns.countplot()代替sns.catplot()