创建彩色概率分布
Create coloured probability distribution
有谁知道如何按照下图中显示的方式对概率分布进行着色。我尝试了各种方法,但没有达到预期的效果。它可以是 R 或 Python,因为我都尝试过。
如果您有 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)
范围内,因此我们通过 height.max()
.
对 bin 值进行归一化
有谁知道如何按照下图中显示的方式对概率分布进行着色。我尝试了各种方法,但没有达到预期的效果。它可以是 R 或 Python,因为我都尝试过。
如果您有 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)
范围内,因此我们通过 height.max()
.