Skip to main content
 首页 » 编程设计

python之根据条件在 Seaborn 中绘制彩色密度图

2024年11月24日15JustinYoung

我正在尝试绘制在特定点改变颜色的核密度图。

我有一个范围从 -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

请您参考如下方法:

我对条形图做了类似的事情,我需要将具有最大值的条着色为红色,这是这样做的。

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