How to plot a superimposed bar chart using matplotlib in python?

前端 未结 3 1946
春和景丽
春和景丽 2021-01-12 20:31

I want to plot a bar chart or a histogram using matplotlib. I don\'t want a stacked bar plot, but a superimposed barplot of two lists of data, for instance I have the follow

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 20:52

    You can produce a superimposed bar chart using plt.bar() with the alpha keyword as shown below.

    The alpha controls the transparency of the bar.

    N.B. when you have two overlapping bars, one with an alpha < 1, you will get a mixture of colours. As such the bar will appear purple even though the legend shows it as a light red. To alleviate this I have modified the width of one of the bars, this way even if your powers should change you will still be able to see both bars.

    plt.xticks can be used to set the location and format of the x-ticks in your graph.

    import matplotlib.pyplot as plt
    import numpy as np
    
    width = 0.8
    
    highPower   = [1184.53,1523.48,1521.05,1517.88,1519.88,1414.98,
                   1419.34,1415.13,1182.70,1165.17]
    lowPower    = [1000.95,1233.37, 1198.97,1198.01,1214.29,1130.86,
                   1138.70,1104.12,1012.95,1000.36]
    
    indices = np.arange(len(highPower))
    
    plt.bar(indices, highPower, width=width, 
            color='b', label='Max Power in mW')
    plt.bar([i+0.25*width for i in indices], lowPower, 
            width=0.5*width, color='r', alpha=0.5, label='Min Power in mW')
    
    plt.xticks(indices+width/2., 
               ['T{}'.format(i) for i in range(len(highPower))] )
    
    plt.legend()
    
    plt.show()
    

    Plot

提交回复
热议问题