简体   繁体   中英

How to decrease hatch density in matplotlib

I need to decrease the density of the hatch in a bar made with matplotlib. The way I add the hatches:

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)

I know that you can increase the density by adding more characters to the pattern, but how can you decrease the density?!

This is a complete hack, but it should work for your scenario.

Basically, you can define a new hatch pattern that becomes less dense the longer the input string. I've gone ahead and adapted the HorizontalHatch pattern for you (note the use of the underscore character):

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

You then have to add it to the list of available hatch patterns:

matplotlib.hatch._hatch_types.append(CustomHorizontalHatch)

In your plotting code you can now use the defined pattern:

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)

Bear in mind that this is not a very elegant solution and might break at any time in future versions. Also my pattern code is just a quick hack as well and you might want to improve on it. I inherit from HorizontalHatch but for more flexibility you would build on HatchPatternBase .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM