首页 > 解决方案 > Python:在 seaborn 中为 1-D swarmplots 着色

问题描述

我正在尝试使用以下数据框制作一维群图(仅显示前几行):

      value    color
0   0.446928    1
1   0.258523    0
2   0.716512    2
3   0.288698    0
4   0.132203    0
5   0.871158    3
6   0.613292    2
7   0.697033    2
8   0.333995    1
9   0.549433    2

使用下面的代码,我制作了一个 1D 群体图:

import matplotlib.pyplot as plt
import seaborn as sns

plt.style.use('ggplot')
sns.swarmplot(x=df['value'], hue=df['color'])

这是生成的图:

在此处输入图像描述

这里的问题是我想为每个组定义颜色,例如从 0 到 0.3 的值应该有红色(比如说),0.3 到 0.5 应该有第二种颜色(比如说绿色)等等。为此,我已经在数据框中定义了颜色列,但是在传递hue=df['color']时,绘图不会生成颜色。我希望我的情节看起来像这样:

在此处输入图像描述

我应该对我的代码进行哪些更改以使我的程序按预期工作?

标签: pythonmatplotlibseaborn

解决方案


生成的散点存储在ax.collections[-1]. 您可以提取它们的 x 坐标,用于np.digitize()将它们分组并使用这些值进行着色:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import pandas as pd
import numpy as np

plt.style.use('ggplot')
df = pd.DataFrame({'value': np.random.uniform(0, 1, 1000)})
ax = sns.swarmplot(x=df['value'])
scatter_dots = ax.collections[-1]
xpos = scatter_dots.get_offsets()[:, 0]
boundaries = [0, .3, .5, .7, 1]  # one more than the number of colors
colors = np.digitize(xpos, boundaries)
scatter_dots.set_array(colors)
scatter_dots.set_cmap(ListedColormap(['crimson', 'limegreen', 'gold', 'skyblue']))
plt.show()

示例图


推荐阅读