【问题标题】:Matplotlib mutli-barchart plotsMatplotlib 多条形图
【发布时间】:2015-02-07 16:41:11
【问题描述】:

有人可以发布一个在一个绘图上绘制图像的示例,它们都是条形图。 每个人都应该在这里看起来像这样: http://matplotlib.org/examples/api/barchart_demo.html

这个例子的问题,它没有说明如何添加另一个图表,如果,如何设置每个图表的配置。

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    您应该使用 fig=plt.figure(),然后添加两个子图 ax=fig.add_subplot(2,2,1) 和 ax2=fig.add_subplot(2,2,2)。之后,您可以使用 ax 和 ax2 完成所有操作。

    您参考的修改示例:

    import numpy as np
    import matplotlib.pyplot as plt
    
    N = 5
    menMeans = (20, 35, 30, 35, 27)
    menStd =   (2, 3, 4, 1, 2)
    
    ind = np.arange(N)  # the x locations for the groups
    width = 0.35       # the width of the bars
    
    fig = plt.figure()
    ax = fig.add_subplot(2,2,1)
    rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)
    
    womenMeans = (25, 32, 34, 20, 25)
    womenStd =   (3, 5, 2, 3, 3)
    rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)
    
    # add some text for labels, title and axes ticks
    ax.set_ylabel('Scores')
    ax.set_title('Scores by group and gender')
    ax.set_xticks(ind+width)
    ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )
    
    ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )
    
    def autolabel(rects):
        # attach some text labels
        for rect in rects:
            height = rect.get_height()
            ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                    ha='center', va='bottom')
    
    autolabel(rects1)
    autolabel(rects2)
    
    ax2 = fig.add_subplot(2,2,2)
    rects3 = ax2.bar(ind, menMeans, width, color='r', yerr=menStd)
    
    womenMeans = (20, 32, 34, 20, 25)
    womenStd =   (3, 7, 2, 3, 3)
    rects4 = ax2.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)
    
    ax2.set_ylabel('Scores_2')
    ax2.set_title('Scores by group and gender_2')
    ax2.set_xticks(ind+width)
    ax2.set_xticklabels( ('G1_2', 'G2_2', 'G3_2', 'G4_2', 'G5_2') )
    
    ax2.legend( (rects1[0], rects2[0]), ('Men_2', 'Women_2') )
    
    def autolabel(rects):
        # attach some text labels
        for rect in rects:
            height = rect.get_height()
            ax2.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                    ha='center', va='bottom')
    
    autolabel(rects3)
    autolabel(rects4)
    
    plt.show()
    

    【讨论】: