首页 > 解决方案 > 创建彩色概率分布

问题描述

有谁知道如何以如下图所示的方式获得概率分布的颜色。我尝试了各种方法,但没有达到预期的结果。它可以是 R 或 Python,因为我都尝试过。

所需的颜色

标签: pythongraphprobability

解决方案


如果您有 bin 值,则可以使用颜色图生成条形颜色:

from scipy import stats
import numpy as np
from matplotlib import pyplot as plt

# generate a normal distribution
values = stats.norm().rvs(10000)

# calculate histogram -> get bin values and locations
height, bins = np.histogram(values, bins=50)

# bar width
width = np.ediff1d(bins)

# plot bar
# to get the desired colouring the colormap needs to be inverted and all values in range (0,1)
plt.bar(bins[:-1] + width/2, height, width*0.8,
        color=plt.cm.Spectral((height.max()-height)/height.max()))

着色的关键是这段代码:plt.cm.Spectral((height.max()-height)/height.max()). 它将颜色图应用于应该在范围内的高度值,(0, 1)因此我们将 bin 值标准化为height.max()

例子


推荐阅读