python - 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']
时,绘图不会生成颜色。我希望我的情节看起来像这样:
我应该对我的代码进行哪些更改以使我的程序按预期工作?
解决方案
生成的散点存储在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()
推荐阅读
- python - Python Traceback(最近一次调用最后一次)错误
- javascript - Javascript / React - 不重复自己的最佳方式
- javascript - 在弹出窗口中显示 php echo 输出
- webpack - Laravel 混合和自定义 javascript 文件的通配符
- assembly - 处理器可以同时进行内存和算术运算吗?
- java - FileNotFoundException 的 Java 无法访问的 catch 块
- java - 如何在java中旋转给定数字的整数?
- powershell - Powershell 路径名变量
- python - 如何使用日志记录模块将 Python 的单元测试模块错误回溯重定向到日志文件?
- curl - 如何通过使用 curl 脚本解析 AQL 来下载工件?