matplotlib 柱狀圖
阿新 • • 發佈:2018-12-16
222
# coding utf-8 # import matplotlib import numpy as np import matplotlib.pyplot as plt import matplotlib import xlrd def read_excel(path): try: list = [] file = xlrd.open_workbook(path) sheet = file.sheet_by_index(0) rows = sheet.row_values for line inrange(0, sheet.nrows): list.append(rows(line)) return list except: pass def fun1(): # population = read_excel(r'renkou2016.xlsx') # 人口列表 population=[['年末總人口(萬人)', 138271.0], ['0-14歲人口(萬人)', 23091.0], ['15-64歲人口(萬人)', 100246.0], ['65歲及以上人口(萬人)', 14933.0]]#測試資料 date= [] name = [] for i in range(0,len(population)): date.append(population[i][1]) name.append(population[i][0]) # 中文亂碼的處理 plt.rcParams['font.sans-serif'] = ['SimHei'] # 步驟一(替換sans-serif字型) plt.rcParams['axes.unicode_minus'] = False # 步驟二(解決座標軸負數的負號顯示問題) # 繪圖 plt.bar(range(4), date, align = 'center',color='steelblue', alpha = 0.8) # 新增軸標籤 plt.ylabel('人口') # 新增標題 plt.title('2016年人口各年齡階段分佈的柱形圖') # 新增刻度標籤 plt.xticks(range(len(date)), name) # 設定Y軸的刻度範圍 plt.ylim([5000,150000]) # 為每個條形圖新增數值標籤 for x, y in enumerate(date): plt.text(x, y+100, '%s' % round(y, 1), ha='center') # 顯示圖形 plt.show() return plt if __name__ == '__main__': plt = fun1() plt.show()