使用分层直方图的Matplotlib

2024-05-16 01:36:10 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在matplotlib/pyplot中制作分层直方图?在

我已经了解了如何将透明与alpha标记一起使用,但我找不到一种将其分层的方法

如果有两个数据集有一个共同的y轴图,那么应该先画出最小的频率,这样它就可以在较大的频率上分层显示。在

透明度不能正常工作,因为它改变了颜色,然后使它与键不匹配。在


Tags: 数据方法标记alphamatplotlib颜色分层直方图
1条回答
网友
1楼 · 发布于 2024-05-16 01:36:10

我想你可以通过根据每个条形图的高度设置其z顺序来获得所需的效果:

import numpy as np
from matplotlib import pyplot as plt

# two overlapping distributions
x1 = np.random.beta(2, 5, 500)
x2 = np.random.beta(5, 2, 500)

fig, ax = plt.subplots(1, 1)
ax.hold(True)

# plot the histograms as usual
bins = np.linspace(0, 1, 20)
counts1, edges1, bars1 = ax.hist(x1, bins)
counts2, edges2, bars2 = ax.hist(x2, bins)

# plot the histograms as lines as well for clarity
ax.hist(x1, bins, histtype='step', ec='k', ls='solid', lw=3)
ax.hist(x2, bins, histtype='step', ec='k', ls='dashed', lw=3)

# set the z-order of each bar according to its relative height
x2_bigger = counts2 > counts1
for b1, b2, oo in zip(bars1, bars2, x2_bigger):
    if oo:
        # if bar 2 is taller than bar 1, place it behind bar 1
        b2.set_zorder(b1.get_zorder() - 1)
    else:
        # otherwise place it in front
        b2.set_zorder(b1.get_zorder() + 1)

plt.show()

enter image description here

相关问题 更多 >