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

Posted

技术标签:

【中文标题】如何使用渐变颜色为分布图的条形着色?【英文标题】:How to color bars of a distribution plot using gradient colors? 【发布时间】:2018-01-13 07:58:15 【问题描述】:

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

在您的代码中,您尝试根据数据值本身为条形着色。但是,直方图显示了 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()

您可以将调用中的 bin 设置为 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()

【讨论】:

谢谢。如果我在开始时使用plt.figure(figsize=(14,8)),我无法调整此图的大小。它总是很小。 我还需要维护25 大小的垃圾箱。在我的代码中,我使用plt.xticks(np.arange(min(df_day_route_veh_counts['time_diff']), max(df_day_route_veh_counts['time_diff'])+100, 25.0))。我怎样才能使这种方法适合您的代码? plt.subplots(figsize=(14,8)) 设置图形大小。 plt.xticks 不设置 bin 大小。它设置轴上刻度的位置。但它也适用于这段代码。如果要更改直方图的 bin 大小,需要使用 np.histogrambins 参数。 我应该手动创建这些垃圾箱吗?我不能只说每个 bin 应该等于 0.1 吗?例如sns.distplot(df['time_diff'],hist="true"plt.xticks 的组合会根据plt.xticks 定义的距离自动创建分箱。 您可以指定 bin 数量或 bin 边缘。后一种情况显示在更新的答案中。

以上是关于如何使用渐变颜色为分布图的条形着色?的主要内容,如果未能解决你的问题,请参考以下文章

如何在sencha touch中为条形图提供渐变颜色和为图表背景提供虚线

maya渐变着色器怎么用

如何在视图控制器的多个视图中添加多个渐变颜色

在 pyqtgraph 中为条形图设置渐变颜色

如何在 Objective-C 中进行颜色着色

如何实时统一地为曲线的各个部分着色?