在直方图中孵化多个数据系列

her*_*cho 3 python numpy matplotlib

当我为直方图着色时,它接受不同颜色的列表,但是,对于阴影,它只接受一个值.

这是代码:

import numpy as np
import matplotlib.pylab as plt


data = [np.random.rand(100) + 10 * i for i in range(3)]
ax1 = plt.subplot(111)

n, bins, patches = ax1.hist(data, 20, histtype='bar',
                        color=['0', '0.33', '0.66'],
                        label=['normal I', 'normal II', 'normal III'],
                        hatch= ['', 'o', '/'])
Run Code Online (Sandbox Code Playgroud)

如何为不同的系列设置不同的舱口?

wfl*_*nny 7

不幸的是,它看起来不像hist支持多系列图的多个阴影.但是,您可以通过以下方式解决这个问题:

import numpy as np
import matplotlib.pylab as plt    

data = [np.random.rand(100) + 10 * i for i in range(3)]
ax1 = plt.subplot(111)

n, bins, patches = ax1.hist(data, 20, histtype='bar',
                        color=['0', '0.33', '0.66'],
                        label=['normal I', 'normal II', 'normal III'])

hatches = ['', 'o', '/']
for patch_set, hatch in zip(patches, hatches):
    for patch in patch_set.patches:
        patch.set_hatch(hatch)
Run Code Online (Sandbox Code Playgroud)

patches返回的对象hist是一个BarContainer对象列表,每个Patch对象包含一组对象(in BarContainer.patches).因此,您可以访问每个补丁对象并明确设置其填充.

或者@MadPhysicist指出你可以plt.setp在每个上使用,patch_set所以循环可以缩短为:

for patch_set, hatch in zip(patches, hatches):
    plt.setp(patch_set, hatch=hatch)
Run Code Online (Sandbox Code Playgroud)