常見統計圖:單條折線圖、多條折線圖、直方圖、柱狀圖、餅狀圖python
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt def init(): mpl.rcParams['font.sans-serif'] = [u'SimHei'] # 正常顯示中文(FangSong/黑體 FangSong/KaiTi) mpl.rcParams['axes.unicode_minus'] = False # 正常顯示負號 # 單線折線圖 def zxt1(x,y): plt.figure(facecolor='w') plt.plot(x, y, 'ro-', label='func1', linewidth=2) plt.legend(loc='upper center') plt.xlabel('X',fontsize=16) plt.ylabel('Y',fontsize=16) plt.scatter(4, 0, color='b') # 標註特殊點 plt.text(4,0,(4,0)) # 標註文本 plt.title('單線折線圖',fontsize=18) plt.grid(True) # 顯示網格 plt.show() # 多線折線圖 def zxt2(x,y1,y2): plt.figure(facecolor='w') plt.plot(x, y1, 'ro-', label='func1', linewidth=2) plt.plot(x, y2, 'g*-', label='func2', linewidth=2) plt.legend(loc='upper center') plt.xlabel('X',fontsize=16) plt.ylabel('Y',fontsize=16) plt.title('多線折線圖',fontsize=18) plt.grid(True) # 顯示網格 plt.show() # 直方圖 def zft(x): plt.figure(facecolor='w') plt.hist(x, bins=10, facecolor='green', align='mid', alpha=0.75) plt.xlabel('X') plt.ylabel('Count') plt.title('直方圖') plt.show() # 柱狀圖 def zzt(x,y): rect = plt.bar(x, y, width=0.5, color="green", align="center") # plt.xticks(x, ('低級','中級','高級','頂級')) # 轉換x軸座標文本 plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("柱狀圖") # plt.grid(True) # 顯示網格 plt.legend((rect,), ("圖例",)) autolabel(rect) plt.show() # 標註柱形圖y值的函數 def autolabel(rects): for rect in rects: height = rect.get_height() plt.text(rect.get_x()+rect.get_width()/2., 1.03*height, "%s" % float(height)) # 餅狀圖 def bzt(x): labels = '大學', '國企', '外資', '民營' explode = [0, 0.1, 0, 0] # 0.1 凸出這部分, plt.axes(aspect=1) # set this , Figure is round, otherwise it is an ellipse plt.pie(x=x, labels=labels, explode=explode, autopct='%3.1f %%', shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6) plt.show() # 繪圖示例 if __name__ == "__main__": init() x = np.linspace(1,10,20) y = (x-4)**2 y1 = (x-4)**2 y2 = 2*x+3 list = [1,1,1,2,5,6,6,7,7,7,7] fracs = [15, 30.55, 44.44, 10] x3 = [1,2,3,4] y3 = [2,4,6,8] zxt1(x,y) # zxt2(x,y1,y2) # zft(list) # zzt(x3, y3) # bzt(fracs)
-------------完-------------函數