Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

python - 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?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...