天天看點

maplotlib畫柱狀圖并添加标簽

import json
from collections import Counter
import matplotlib.pyplot as plt
import matplotlib as mpl


def extract(fpath):
    # 提取資料
    # 傳回包含有兩個元素的元組組成的清單
    
    with open(fpath, encoding='utf-8') as f:
        data = json.load(f)
    
    company_info = []
    for item in data['erDataList']:
        company_info.append((item['city'], item['address']))
    
    return company_info


def autolabel(rects, ax, xpos='center'):
    # 給柱狀圖中的每一條柱添加标簽
    
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha="center",
                    va="bottom")


def makeChart(data):
    # 制作圖表

    citys = [item[0] for item in data]
   # addrs = [item[1] for item in data]
    
    counter = Counter(citys)
    
    # 設定畫布大小,機關是 inch
    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(1, 1, 1)
    rects = ax.bar(x=list(counter.keys()),
                   height=list(counter.values()))
    ax.set_xlabel("城市分布")
    ax.set_ylabel("2004年成立企業數")
    ax.set_title("廣東省2004年各市新成立企業數量")
    autolabel(rects, ax)
    plt.show()


if __name__ == '__main__':
    
    # 設定以正常顯示中文字型
    mpl.rcParams['font.sans-serif'] = 'SimHei'   
    fpath = '廣西2004.json'
    data = extract(fpath)
    makeChart(data)
           

(本文完)

--------------------------------------------------------------------------------------------------------------------------

緻虛極,守靜笃

使用我的阿裡雲幸運券,購買阿裡雲ECS有優惠:阿裡雲幸運券

>>>>> 騰訊雲新使用者優惠

<<<<<