如何降低 matplotlib 中的孵化密度 [英] How to decrease hatch density in matplotlib
问题描述
我需要降低用 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?!
推荐答案
这是一个完整的 hack,但它应该适用于您的场景.
This is a complete hack, but it should work for your scenario.
基本上,您可以定义一个新的填充图案,输入图案越长,填充图案的密度就越低.我已经为您修改了 HorizontalHatch
模式(注意下划线字符的使用):
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)
请记住,这不是一个非常优雅的解决方案,并且可能会在未来版本中随时中断.同样,我的模式代码也只是一个快速的技巧,您可能需要对其进行改进.我继承自 HorizontalHatch
,但要获得更大的灵活性,您可以在 HatchPatternBase
上构建.
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
.
这篇关于如何降低 matplotlib 中的孵化密度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!