如何降低matplotlib中的孵化密度

Dro*_*man 9 python matplotlib

我需要降低用matplotlib制成的条形舱口的密度.我添加阴影的方式:

kwargs = {'hatch':'|'}
rects2 = ax.bar(theta, day7, width,fill=False, align='edge', alpha=1, **kwargs)

kwargs = {'hatch':'-'}
rects1 = ax.bar(theta, day1, width,fill=False, align='edge', alpha=1, **kwargs)
Run Code Online (Sandbox Code Playgroud)

我知道你可以通过在图案中添加更多字符来增加密度,但是如何降低密度?!

小智 8

这是一个完整的黑客攻击,但它应该适用于您的场景.

基本上,您可以定义一个新的填充图案,输入字符串越长,密度越小.我已经开始HorizontalHatch为你调整模式了(注意使用下划线字符):

class CustomHorizontalHatch(matplotlib.hatch.HorizontalHatch):
    def __init__(self, hatch, density):
        char_count = hatch.count('_')
        if char_count > 0:
            self.num_lines = int((1.0 / char_count) * density)
        else:
            self.num_lines = 0
        self.num_vertices = self.num_lines * 2
Run Code Online (Sandbox Code Playgroud)

然后,您必须将其添加到可用的填充图案列表中:

matplotlib.hatch._hatch_types.append(CustomHorizontalHatch)
Run Code Online (Sandbox Code Playgroud)

在您的绘图代码中,您现在可以使用已定义的模式:

kwargs = {'hatch':'_'}  # same as '-'
rects2 = ax.bar(theta, day7, width,fill=False, align='edge', alpha=1, **kwargs)

kwargs = {'hatch':'__'}  # less dense version
rects1 = ax.bar(theta, day1, width,fill=False, align='edge', alpha=1, **kwargs)
Run Code Online (Sandbox Code Playgroud)

请记住,这不是一个非常优雅的解决方案,可能会在未来的版本中随时中断.此外,我的模式代码也是一个快速的黑客,你可能想要改进它.我继承了,HorizontalHatch但为了更多的灵活性,你会继续HatchPatternBase.