如何在matplotlib中降低图案密度

11

我需要在使用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)

我知道通过添加更多的字符到一个模式中可以增加密度,但是如何减少密度?!


你能给这个 hatch 添加空格吗? - TryPyPy
1个回答

9
这是一个完整的技巧,但它应该适用于您的情况。基本上,您可以定义一个新的填充图案,随着输入字符串越长,变得更加稀疏。我已经为您调整了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

您需要将其添加到可用填充图案列表中:

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

matplotlib.hatch._hatch_types.append(CustomHorizontalHatch)

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

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)

记住,这不是一个非常优雅的解决方案,并且在未来的版本中随时可能会出现问题。我的模式代码也只是一个快速的技巧,您可能希望对其进行改进。我继承自HorizontalHatch,但为了更灵活,您可以基于HatchPatternBase构建。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接