python - 具有两种颜色的 Matplotlib 绘图分布

标签 python matplotlib probability

此处的目标是将高于某个阈值的值着色为一种颜色,将低于该阈值的值着色为另一种颜色。下面的代码试图将它分成两个直方图,但只有当阈值为 50% 时它才会看起来平衡。我假设我必须使用 discreetlevel 变量。

finalutilityrange 是一些带有一堆值的向量(你必须生成它来测试代码),我正在尝试绘制它。值 deter 是确定它们是蓝色还是红色的值。 discreetlevel 就是我想要的 bin 数量。

import random
import numpy as np
import matplotlib.pyplot as plt

discreetlevel = 10
deter = 2

for x in range(0,len(finalutilityrange)):
    if finalutilityrange[x-1]>=deter:
        piraterange.append(finalutilityrange[x-1])
    else:
        nonpiraterange.append(finalutilityrange[x-1])

plt.hist(piraterange,bins=discreetlevel,normed=False,cumulative=False,color = 'b')
plt.hist(nonpiraterange,bins=discreetlevel),normed=False,cumulative=False,color = 'r')
plt.title("Histogram")
plt.xlabel("Utlity")
plt.ylabel("Probability")
plt.show()

最佳答案

这个解决方案比@user2699 的要复杂一些。我只是为了完整性而展示它。您可以完全控制 hist 返回的补丁对象,因此如果您可以确保您使用的阈值恰好位于 bin 边缘,则很容易更改为所选补丁的颜色。您可以这样做,因为 hist 可以接受一系列 bin 边缘作为 bins 参数。

import numpy as np
from matplotlib import pyplot as plt 

# Make sample data
finalutilityrange = np.random.randn(100)
discreetlevel = 10
deter = 0.2

# Manually create `discreetlevel` bins anchored to  `deter`
binsAbove = round(discreetlevel * np.count_nonzero(finalutilityrange > deter) / finalutilityrange.size)
binsBelow = discreetlevel - binsAbove
binwidth = max((finalutilityrange.max() - deter) / binsAbove,
               (deter - finalutilityrange.min()) / binsBelow)
bins = np.concatenate([
           np.arange(deter - binsBelow * binwidth, deter, binwidth),
           np.arange(deter, deter + (binsAbove + 0.5) * binwidth, binwidth)
])

# Use the bins to make a single histogram
h, bins, patches = plt.hist(finalutilityrange, bins, color='b')

# Change the appropriate patches to red
plt.setp([p for p, b in zip(patches, bins) if b >= deter], color='r')

结果是具有不同颜色 bin 的同质直方图:

enter image description here

如果您没有锚定 deter,垃圾箱可能会更宽一些。第一个或最后一个 bin 通常会稍微超出数据的边缘。

关于python - 具有两种颜色的 Matplotlib 绘图分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40222996/

相关文章:

r - 在 R 中使用多项式函数进行多项式回归

java - 检测数字是否在特定范围内

matplotlib - 关闭轴,保持刻度

algorithm - 维特比搜索 - 假设概率

python - 如何实现串行设备使用的自定义代码页,以便我可以在 Python 中将文本转换为该代码页?

python - conv1D 中的形状尺寸

pandas - 如何在matplotlib pandas中将两个文件的两个条形图组合在一张图中

python - 在同一轴上绘制不同的面部颜色

python - 在 openshift 中导入 python 模块

python - Ctypes:获取指向结构体字段的指针