matplotlib學習筆記【12】:matplotlib在一個橫座標刻度下畫出多個條形圖bar

今天做了一些簡單的數據分析。數據如下:

代碼:

 def view_all2(self,data):
        hw_server = data[(data['name'] == 'HW') & (data['device'] == 'server')]
        hw_server_count = hw_server.device.count()
        tx_server = data[(data['name'] == 'TX') & (data['device'] == 'server')]
        tx_server_count = tx_server.device.count()
        h3_server = data[(data['name'] == 'H3') & (data['device'] == 'server')]
        h3_server_count = h3_server.device.count()
        hw_save = data[(data['name'] == 'HW') & (data['device'] == 'save')]
        hw_save_count = hw_save.device.count()
        tx_save = data[(data['name'] == 'TX') & (data['device'] == 'save')]
        tx_save_count = tx_save.device.count()
        h3_save = data[(data['name'] == 'H3') & (data['device'] == 'save')]
        h3_save_count = h3_save.device.count()
        hw_firewall = data[(data['name'] == 'HW') & (data['device'] == 'firewall')]
        hw_firewall_count = hw_firewall.device.count()
        tx_firewall = data[(data['name'] == 'TX') & (data['device'] == 'firewall')]
        tx_firewall_count = tx_firewall.device.count()
        h3_firewall = data[(data['name'] == 'H3') & (data['device'] == 'firewall')]
        h3_firewall_count = h3_firewall.device.count()
        a = ['TX','H3','HW']
        y1 = [tx_server_count,h3_server_count,hw_server_count]
        x1 = list(range(len(['TX','H3','HW'])))
        plt.figure(figsize=(20,10))
        plt.bar(x1,y1,facecolor='#9999ff', edgecolor='white',width=0.2,label='server')
        for x, y in zip(x1, y1):
            plt.text(x, y + 0.05, '%d' % y, ha='center', va='bottom')
        x2 = [i+0.2 for i in x1]
        y2 = [tx_save_count,h3_save_count,hw_save_count]
        plt.bar(x2,y2,facecolor='#00BFFF', edgecolor='white', width=0.2, label='save')
        for x, y in zip(x2, y2):
            plt.text(x, y + 0.05, '%d' % y, ha='center', va='bottom')
        x3 = [i+0.4 for i in x1]
        y3 = [tx_firewall_count,h3_firewall_count,hw_firewall_count]
        plt.bar(x3,y3,facecolor='#FF1493', edgecolor='white', width=0.2, label='firewall')
        for x, y in zip(x3, y3):
            plt.text(x, y + 0.05, '%d' % y, ha='center', va='bottom')
        plt.xticks(x2,a) # 設置x座標軸上的顯示
        plt.legend(loc='upper right')
        plt.show()


if __name__ == '__main__':
    data = pd.read_csv('testData.csv')
    ds = data_solution()
    ds.view_all2(data)

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章