Search code examples
pythonmatplotlibbar-chartpie-chart

How to draw a horizontal percentage bar plot with matplotlib?


Is it possible to draw a similar graph using matplotlib that I've attached below?

enter image description here


Solution

  • From: https://matplotlib.org/gallery/lines_bars_and_markers/broken_barh.html

    import matplotlib.pyplot as plt
    import matplotlib.patches as mpatches
    
    fig, ax = plt.subplots()
    
    start = 0
    never = 54
    seldom = 43
    undecided = 3
    
    ax.broken_barh([(start, never), (never, never+seldom), (never+seldom, never+seldom+undecided)], [10, 9], facecolors=('#6259D8', '#E53F08', '#FDB200'))
    ax.set_ylim(5, 15)
    ax.set_xlim(0, 100)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.set_yticks([15, 25])
    ax.set_xticks([0, 25, 50, 75, 100])
    
    ax.set_axisbelow(True) 
    
    ax.set_yticklabels(['Q1'])
    ax.grid(axis='x')
    ax.text(never-6, 14.5, "54%", fontsize=8)
    ax.text((never+seldom)-6, 14.5, "43%", fontsize=8)
    ax.text((never+seldom+undecided)+2, 14.5, "3%", fontsize=8)
    
    fig.suptitle('This is title of the chart', fontsize=16)
    
    leg1 = mpatches.Patch(color='#6259D8', label='Never')
    leg2 = mpatches.Patch(color='#E53F08', label='Seldom')
    leg3 = mpatches.Patch(color='#FDB200', label='Undecided')
    ax.legend(handles=[leg1, leg2, leg3], ncol=3)
    
    plt.show()
    

    This is the result:

    Result