zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    业余无线电A类考试准备笔记
    关于互联网技术基层绩效管理的一些思考
    适合产品经理的十本书 From 俞军
    从敏捷开发到微服务,maybe再到中台
    Golang内存模型
    CSS中的那点事儿(一)--- CSS中的单位2
    CSS中的那点事儿(一)--- CSS中的单位1
    design.js
    model.js
    云技术相关的概念
  • 原文地址:https://www.cnblogs.com/wuzhiblog/p/10990119.html
Copyright © 2011-2022 走看看