How to hatch broken_barh on matplotlib python?

2.1k Views Asked by At

I would like to use hatching in broken_barh of matplotlib. What I want is to for different color in the plot to have different hatching pattern. I tried to add as a dictionary but wasn't successful, anyone knows what is the correct way? this is a sample code from matplotlib website.

""" Make a "broken" horizontal bar plot, i.e., one with gaps """

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='blue', hatch='o')
ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),
               facecolors=('red', 'yellow', 'green'), hatch='//')
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)
ax.set_xlabel('seconds since start')
ax.set_yticks([15, 25])
ax.set_yticklabels(['Bill', 'Jim'])
ax.grid(True)
ax.annotate('race interrupted', (61, 25),
            xytext=(0.8, 0.9), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            fontsize=16,
            horizontalalignment='right', verticalalignment='top')

plt.show()

I want to have different hatching for different color, but it is not possible:
I want to have different hatching for different color, but it is not possible

I would appreciate if someone could give me a hint how to do that?

1

There are 1 best solutions below

0
On BEST ANSWER

broken_barh does not allow to set different hatches. But since a broken bar is just many single bars, you can plot single bars with different hatches.

import matplotlib.pyplot as plt

def brokenhatchbar(xs, y, ax=None, **kw):
    if not ax: ax=plt.gca()
    hatches = kw.pop("hatch", [None]*len(xs))
    facecolors = kw.pop("facecolors", [None]*len(xs))
    edgecolors = kw.pop("edgecolors", [None]*len(xs))
    for i, x in enumerate(xs):
        ax.barh(bottom=y[0], width=x[1], height=y[1], left=x[0],
                facecolor=facecolors[i], edgecolor=edgecolors[i], hatch=hatches[i])

fig, ax = plt.subplots()
brokenhatchbar([(110, 30), (150, 10)], (10, 9), facecolors=['blue','blue'], hatch=['o','////'])
brokenhatchbar([(10, 50), (100, 20), (130, 10)], (20, 9),
               facecolors=('red', 'yellow', 'green'), hatch=('//', 'o', '+'))
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)
ax.set_xlabel('seconds since start')

ax.grid(True)

plt.show()

enter image description here