簡體   English   中英

Python:為 seaborn 中的一維群圖着色

[英]Python: Coloring 1-D swarmplots in seaborn

我正在嘗試使用以下數據框制作一維群 plot(僅顯示前幾行):

      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

使用下面的代碼,我制作了一個一維群 plot:

import matplotlib.pyplot as plt
import seaborn as sns

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

這是生成的 plot:

在此處輸入圖像描述

這里的問題是我想為每個組定義顏色,例如 0 到 0.3 的值應該有紅色(比如),0.3 到 0.5 應該有第二種顏色(比如綠色)等等。 為此,我在 dataframe 中定義了顏色列,但在傳遞hue=df['color']時,plot 沒有生成顏色。 我希望我的 plot 看起來像這樣:

在此處輸入圖像描述

我應該對我的代碼進行哪些更改才能使我的程序按預期運行?

生成的散點存儲在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()

示例圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM