根据条件在Seaborn中绘制多色密度图

时间:2019-04-02 00:40:55

标签: python data-visualization seaborn

我正在尝试绘制一个内核密度图,该图在某个点会改变颜色。

我有一个介于-3到3之间的连续变量,并且希望0以下的数据显示为蓝线和阴影区域,而0以上的数据显示为红色。我尝试创建与数据中每个点相对应的颜色列表或一系列颜色,但是Seaborn的kdeplot颜色选项似乎不允许使用数组。我也尝试将0上下的数据进行分组,但这绘制了两个明显独立的分布,我只想要一个。

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

sample = np.random.uniform(low=-3.0, high=3.0, size=(100,))
df = pd.DataFrame(sample, columns = ['scores'])

def plot_group(group):
    global ax
    c = 'b' if (group['scores'] < 0).all() else 'r'
    sns.kdeplot(group['scores'], color = c, shade = True)

colors = np.where(df['scores'] < 0, 'b', 'r')
df.groupby(colors).apply(plot_group)
sns.despine(top = True, right = True, left = True)
plt.setp(axes, yticks=[])

我希望单个连续分布的颜色在零附近有不同的颜色,但是我得到的是两个单独的图。 Here's the incorrect output that I'm generating

1 个答案:

答案 0 :(得分:0)

我已经对条形图进行了类似的操作,我需要用最大的红色将条形着色为红色,

import seaborn as sns

colors = ['grey' if (x < max(values)) else 'red' for x in values ]
sns.barplot(x=labels, y=values, palette=colors)