How to plot multiple horizontal bars in one chart with matplotlib

前端 未结 2 1982
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 13:20

Can you help me figure out how to draw this kind of plot with matplotlib?

I have a pandas data frame object representing the table:

Graph       n            


        
2条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 14:00

    It sounds like you want something very similar to this example: http://matplotlib.org/examples/api/barchart_demo.html

    As a start:

    import pandas
    import matplotlib.pyplot as plt
    import numpy as np
    
    df = pandas.DataFrame(dict(graph=['Item one', 'Item two', 'Item three'],
                               n=[3, 5, 2], m=[6, 1, 3])) 
    
    ind = np.arange(len(df))
    width = 0.4
    
    fig, ax = plt.subplots()
    ax.barh(ind, df.n, width, color='red', label='N')
    ax.barh(ind + width, df.m, width, color='green', label='M')
    
    ax.set(yticks=ind + width, yticklabels=df.graph, ylim=[2*width - 1, len(df)])
    ax.legend()
    
    plt.show()
    

    enter image description here

提交回复
热议问题