如何使用渐变颜色为分布图着色条?

时间:2017-08-05 13:59:19

标签: python python-2.7 pandas matplotlib seaborn

我有以下数据框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)

1 个答案:

答案 0 :(得分:1)

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

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

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()

enter image description here

您可以在调用np.histogram时设置垃圾箱,例如对于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()

enter image description here