How to fix bar width in this matplotlib plot

后端 未结 1 551
南笙
南笙 2020-12-20 08:09

Could someone please tell me how to modify this Python code that uses matplotlib such that the width of the bars will stay constant regardless of how many scores are plotted

相关标签:
1条回答
  • 2020-12-20 08:22

    The bars are the same width! The reason they don't look the same is because you are using this line:

    index = np.arange(n_groups)
    

    This will change your x-values and hence the scale of your x-axis. To counteract this effect you can either change the limits of your x-axis, or make the bar width depend on the number of scores, so for example if a width of 0.35 works for 10 scores then if you double the number of scores you would half the bar width (and vice versa). You can see how either changing the axis limits or bar width gives bars that look the same width:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # make some dummy data
    scores_reading = np.random.randint(50,100,10)
    scores_math = np.random.randint(50,100,10)
    
    fig = plt.figure(figsize=(16,5))
    bar_width = 0.35
    index = np.arange(10)
    
    ax1 = fig.add_subplot(1,4,1)
    ax1.bar(index, scores_reading, bar_width, fc='b', edgecolor='none')
    ax1.bar(index+bar_width, scores_math, bar_width, fc='r', edgecolor='none')
    ax1.set_xlim(0,10)
    ax1.set_title('Original - 10 scores')
    
    ax2 = fig.add_subplot(1,4,2)
    ax2.bar(index[:5], scores_reading[:5], bar_width, fc='b', edgecolor='none')
    ax2.bar(index[:5]+bar_width, scores_math[:5], bar_width, fc='r', edgecolor='none')
    ax2.set_title('Original - 5 scores')
    
    ax3 = fig.add_subplot(1,4,3)
    ax3.bar(index[:5], scores_reading[:5], bar_width, fc='b', edgecolor='none')
    ax3.bar(index[:5]+bar_width, scores_math[:5], bar_width, fc='r', edgecolor='none')
    ax3.set_xlim(0,10)
    ax3.set_title('Changed limit - 5 scores')
    
    ax4 = fig.add_subplot(1,4,4)
    ax4.bar(index[:5], scores_reading[:5], bar_width/2., fc='b', edgecolor='none')
    ax4.bar(index[:5]+bar_width, scores_math[:5], bar_width/2., fc='r', edgecolor='none')
    ax4.set_title('Changed width - 5 scores')
    
    fig.show()
    

    0 讨论(0)
提交回复
热议问题