python绘图实例

python Plt实例

背景:

业务的健身数据,有一个字段是其他附加信息,格式是json,需要查出该字段,解出json,拿到目标数据,
按要求聚合,如燃脂是0.25的有几个

目的:

要验证运营页面的概览数据是否正确

策略:

从表中查出数据,格式化,用plt绘制,与被测页面的图形数据对比

代码如下:


# coding: utf8
import MySQLdb
import json
import pandas as pd
import numpy as np
import time
import matplotlib.pyplot as plt
import pylab
from PIL import Image

import random

"""var (
    dbhostsip  = "ip"
    dbusername = "root"
    dbpassowrd = "12345"
    dbname     = "datacenter"
)
"""


def getfatburning():
    # 打开数据库连接
    db = MySQLdb.connect("ip", "root", "123456","datacenter", charset='utf8')
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    # SQL 查询语句
    sql = "SELECT ext FROM datacenter.mdata where cid=10002"

    #try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    templist =[]
    for row in results:
        temp=json.loads(row[0])
        templist.append(float(temp["data"]["fatBurning"]))
    tempdic ={}
    # temptup=[]
    cot=0
    for i in range(len(templist)):
        tempdic[templist[i]]= templist.count(templist[i])
    for i in tempdic:
        cot = cot+tempdic[i]
    print cot

    d_order=sorted(tempdic.iteritems(),key=lambda x:x[0],reverse=False)  
    print d_order


    db.commit()
    # 关闭数据库连接
    db.close()
    return d_order

def ShowPlt(fatburning):
    fat ={}
    datalist=[]
    countlist=[]
    for i in range(len(fatburning)):
        datalist.append(fatburning[i][0])
        countlist.append(fatburning[i][1])
    fat["data"]=datalist
    fat["count"]=countlist

    fig = plt.figure()
    ax1 = fig.add_subplot() # 画2行1列个图形的第1个
    bar_width = 0.003#bar 宽度值
    z1=plt.bar(fat["data"][0:20],fat["count"][0:20],bar_width,tick_label=fat["data"][0:20],label='fatburning',fc='G',)#第一个bar
    for a, b in zip(fat["data"][0:20], fat["count"][0:20]):#zip将传入的数据打包成元祖,循环添加数字
        plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', color='r',fontsize=10)#标注的x轴起点,y轴起点,float位数,水平位置,垂直位置,颜色,字体大小)
    fig.autofmt_xdate()#主动调节X轴标注,避免拥挤
    plt.legend(loc='upper left')#显示图注,不调用legend()方法设置了labe也不会显示    
    plt.show()

if __name__ == '__main__':

    fatburning=getfatburning()
    ShowPlt(fatburning)

绘制的图如下:

python绘图实例_第1张图片
验证结果一致,测试通过!

你可能感兴趣的:(python,python)