Skip to main content
 首页 » 编程设计

python之如何使用渐变颜色为分布图的条形着色

2025年02月15日8zengkefu

我有以下数据框df:

time_diff   avg_trips_per_day 
0.450000    1.0 
0.483333    1.0 
0.500000    1.0 
0.516667    2.0 
0.533333    5.0 

然后我创建一个分布图,如下所示 ax = sns.distplot(df['time_diff'],hist="true"。

我想使用渐变为条形着色:较深的颜色应该分配给较高概率的值。

我试过这样做,但没有成功:

norm = plt.Normalize(df["time_diff"].values.min(), df["time_diff"].values.max()) 
colors = plt.cm.YlGnBu(norm(df_imh_unique["time_diff"]))  
ax = sns.distplot(df['time_diff'],hist="true", color=colors) 

请您参考如下方法:

在您的代码中,您试图根据数据值本身为条形图着色。但是,直方图显示了 bin 内值的频率。因此,您需要使用频率来确定条形的颜色。

这在分离直方图和绘图时更容易理解。

import numpy as np 
import matplotlib.pyplot as plt 
 
data = np.random.rayleigh(size=30) 
 
hist, edges = np.histogram(data) 
 
norm = plt.Normalize(hist.min(), hist.max()) 
colors = plt.cm.YlGnBu(norm(hist))  
 
fig, ax = plt.subplots() 
ax.bar(edges[:-1], hist, np.diff(edges), color=colors, ec="k", align="edge") 
 
plt.show() 

您可以在调用 np.histogram 时设置 bins,例如对于 0.1 个大垃圾箱,您将使用

bins = np.arange(0, data.max()+0.1, 0.1) 
hist, edges = np.histogram(data, bins=bins) 

由于 seaborn distplot 结合了直方图和绘图这两个步骤,因此只能在创建绘图后设置条形颜色。这当然不是最优的,但为了完整起见,使用现有 distplot 的解决方案可能如下所示:

import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
 
data = np.random.rayleigh(size=30) 
 
ax = sns.distplot(data) 
 
vals = np.array([rec.get_height() for rec in ax.patches]) 
norm = plt.Normalize(vals.min(), vals.max()) 
colors = plt.cm.YlGnBu(norm(vals)) 
 
for rec, col in zip(ax.patches, colors): 
    rec.set_color(col) 
 
plt.show()