Search code examples
pythonmatplotlibplotpandas

How do I plot hatched bars using pandas?


I am trying to achieve differentiation by hatch pattern instead of by (just) colour. How do I do it using pandas?

It's possible in matplotlib, by passing the hatch optional argument as discussed here. I know I can also pass that option to a pandas plot, but I don't know how to tell it to use a different hatch pattern for each DataFrame column.

df = pd.DataFrame(rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='bar', hatch='/');

enter image description here

For colours, there is the colormap option described here. Is there something similar for hatching? Or can I maybe set it manually by modifying the Axes object returned by plot?


Solution

  • Plot the grouped bars with pandas.DataFrame.plot, and then iterate through the bar patches, to add the hatches.

    Tested in python 3.11.4, pandas 2.1.0, matplotlib 3.7.2

    import pandas as pd
    
    df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
    
    ax = df.plot(kind='bar', legend=False, figsize=(10, 6), rot=0, width=0.8)
    
    bars = ax.patches
    hatches = ''.join(h*len(df) for h in 'x/O.')
    
    for bar, hatch in zip(bars, hatches):
        bar.set_hatch(hatch)
    
    ax.legend(loc='lower center', ncol=4, bbox_to_anchor=(0.5, -0.15))
    

    enter image description here