python如何利用matplotlib繪制并列雙柱狀圖并標注數(shù)值
項目場景:
Python項目需要畫兩組數(shù)據(jù)的雙柱狀圖,以下以一周七天兩位小朋友吃糖顆數(shù)為例進行演示,用matplotlib庫實現(xiàn)
代碼:
import matplotlib import matplotlib.pyplot as plt import numpy as np def drawHistogram(): matplotlib.rc("font", family='MicroSoft YaHei') list1 = np.array([5, 2, 1, 0, 8, 0, 6]) # 柱狀圖第一組數(shù)據(jù) list2 = np.array([9, 5, 1, 2, 9, 2, 0]) # 柱狀圖第二組數(shù)據(jù) length = len(list1) x = np.arange(length) # 橫坐標范圍 listDate = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] plt.figure() total_width, n = 0.8, 2 # 柱狀圖總寬度,有幾組數(shù)據(jù) width = total_width / n # 單個柱狀圖的寬度 x1 = x - width / 2 # 第一組數(shù)據(jù)柱狀圖橫坐標起始位置 x2 = x1 + width # 第二組數(shù)據(jù)柱狀圖橫坐標起始位置 plt.title("一周每天吃悠哈軟糖顆數(shù)柱狀圖") # 柱狀圖標題 # plt.xlabel("星期") # 橫坐標label 此處可以不添加 plt.ylabel("吃悠哈軟糖顆數(shù)(個)") # 縱坐標label plt.bar(x1, list1, width=width, label="小s吃糖數(shù)") plt.bar(x2, list2, width=width, label="小y吃糖數(shù)") plt.xticks(x, listDate) # 用星期幾替換橫坐標x的值 plt.legend() # 給出圖例 plt.show() if __name__ == '__main__': drawHistogram()
效果圖:
擴展功能及代碼:
擴展功能一
如果橫坐標標簽比較長或是文字比較多,以一定角度傾斜展示,上文中代碼這一行:
plt.xticks(x, listDate)
可以改為:
plt.xticks(x, listDate, rotation=30) # rotation為標簽旋轉(zhuǎn)角度
橫坐標標簽旋轉(zhuǎn)30°效果如下:
橫坐標標簽旋轉(zhuǎn)90°效果如下:
擴展功能二
如果希望具體的數(shù)據(jù)值展示在柱狀圖中,可以在代碼 plt.legend()
前加入如下代碼:
for a, b in zip(x1, list1): plt.text(a, b + 0.1, '%.0f' % b, ha='center', va='bottom', fontsize=7) for a, b in zip(x2, list2): plt.text(a, b + 0.1, '%.0f' % b, ha='center', va='bottom', fontsize=7)
加了具體數(shù)值的柱狀圖效果如下:
補充:Python畫圖實現(xiàn)同一結(jié)點多個柱狀圖
import numpy as np x = [1,2] #橫坐標 y = [3,4] #第一個縱坐標 y1 = [5,6] #第二個縱坐標 x = np.arange(len(x)) #首先用第一個的長度作為橫坐標 width = 0.05 #設置柱與柱之間的寬度 fig,ax = plt.subplots() ax.bar(x,y,width,alpha = 0.9) ax.bar(x+width,y1,width,alpha = 0.9,color= 'red') ax.set_xticks(x +width/2)#將坐標設置在指定位置 ax.set_xticklabels(x)#將橫坐標替換成 plt.show()
后續(xù)有時間再繼續(xù)補充擴展功能哦~
總結(jié)
到此這篇關于python如何利用matplotlib繪制并列雙柱狀圖并標注數(shù)值的文章就介紹到這了,更多相關python matplotlib繪制并列雙柱狀圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python獲取網(wǎng)頁中所有圖片并篩選指定分辨率的方法
下面小編就為大家分享一篇python獲取網(wǎng)頁中所有圖片并篩選指定分辨率的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

使用python將請求的requests headers參數(shù)格式化方法

Pandas 對Dataframe結(jié)構(gòu)排序的實現(xiàn)方法

python 爬取古詩文存入mysql數(shù)據(jù)庫的方法