numpy pandas matplotlib和django结合,将matplotlib图片显示到HTML上

首先进行效果展示:

numpy pandas matplotlib和django结合,将matplotlib图片显示到HTML上_第1张图片

numpy pandas matplotlib和django结合,将matplotlib图片显示到HTML上_第2张图片

Django文件布局:

numpy pandas matplotlib和django结合,将matplotlib图片显示到HTML上_第3张图片

views.py

from django.shortcuts import render,HttpResponse
from app1 import BPLackAnalysis
import pandas as pd
import matplotlib.pyplot as plt
import base64
from io import BytesIO

def multiChart(data,sigma_spec):
    plt.figure(figsize=(12,9))
    plt.subplot(311)
    plt.title("CTC Array FAB H3PO4 Monitor for BP Lack")
    plt.plot(data["time"],data["mean"],color="b",marker="*")
    plt.subplot(312)
    data["slope_spec"]=0
    plt.title("$mean{(y2-y1)}$")
    plt.plot(data["time"],data["slope"],color="b")
    plt.plot(data["time"],data["slope_spec"],color="r")
    plt.subplot(313)
    data["sigma_spec"]=sigma_spec
    plt.title("3$sigma$")
    plt.plot(data["time"],data["3sigma"],color="b")
    plt.plot(data["time"],data["sigma_spec"],color="r")
    buffer = BytesIO()
    plt.savefig(buffer)
    plot_data = buffer.getvalue()
    return plot_data

def aaa():
    pass

def index(request):
    if request.method=="POST":
        group_num = 120
        sigma_spec = 0.5
        file_in_path = request.POST.get("file_in_path")
        file_out_path = request.POST.get("file_out_path")
        group_num = request.POST.get("group_num")
        sigma_spec = request.POST.get("sigma_spec")
        print(file_in_path)
        print(group_num)
        try:
            in_file = pd.read_excel(file_in_path)
            print("123")
            data = BPLackAnalysis.dataArrange(in_file,int(group_num))
            data["time"] = data["time"].astype(str)
            print(data.head())
            #将matplotlib图片转换为HTML
            plot_data = multiChart(data,sigma_spec)
            imb = base64.b64encode(plot_data)#对plot_data进行编码
            ims = imb.decode()
            imd = "data:image/png;base64,"+ims
            #iris_im = """""" % imd
            temp_time = []
            temp_H3PO4 = []
            cnt=0
            for i in range(len(data["slope"])-3):
                if data["slope"][i] < 0 and data["slope"][i+1] < 0 and data["slope"][i+2] < 0:
                    cnt+=1
                    temp_time.insert(0,data["time"][i+2])
                    #只保留两位小数
                    temp_H3PO4.insert(0,round(data["mean"][i+2],2))
                    i+=3
            # 保存清洗后数据
            data.to_excel(file_out_path, sheet_name="data")
            print("OK",temp_time,cnt)
            return render(request, "bplack.html",{"img":imd,"temp_time":temp_time,"cnt":cnt,"temp_H3PO4":temp_H3PO4})
        except:
            ret= "文件读取失败,请确认文件路径是否正确!"+r"正确格式示范:C:\Users\raylu\Desktop\ArrayBP\BPLack.xlsx"
            return HttpResponse(ret)
    else:
        return render(request, "index.html")

 

BPLackAnalysis.py

import numpy as np
import pandas as pd
import xlrd
import datetime
import matplotlib.pyplot as plt

#数据清洗,num为定义母数
def dataArrange(data,num):
    new_data = pd.DataFrame({"time":data["start"],"mean":data["mean"]})
    ls1,ls2,ls3,ls4 = [],[],[],[]
    len_data = len(new_data["time"])
    for i in range(0,int(len_data/num)):
        ls1.insert(0,new_data["time"][len_data-1-i*num])
        #H3PO4 mean
        ls2.insert(0,new_data["mean"][(len_data-1-(i+1)*num):(len_data-1-i*num)].mean())
        #H3PO4 mean: this - last
        if i == 0:
            ls3.insert(0,0)
        else:
            ls3.insert(0,ls2[1]-ls2[0])
        #3 sigma
        ls4.insert(0,new_data["mean"][(len_data-1-(i+1)*num):(len_data-1-i*num)].std()*3)
    return pd.DataFrame({"time":ls1,"mean":ls2,"slope":ls3,"3sigma":ls4})

#时间转换
def timeTrans(data):
    data["time"] = data["time"].apply(
        lambda x:datetime.datetime.strptime(
            x[0:4]+"-"+x[4:6]+"-"+x[6:8]+" "+x[8:10]+":"+x[10:12]+":"+x[12:14],
            "%Y-%m-%d %H:%M:%S")
    )
    return data

#多图绘制
def multiChart(data,sigma_spec):
    plt.figure(figsize=(12,10))
    plt.subplot(311)
    plt.title("CTC Array FAB H3PO4 Monitor for BP Lack")
    plt.plot(data["time"],data["mean"],color="b",marker="*")
    plt.subplot(312)
    data["slope_spec"]=0
    plt.title("$mean{(y2-y1)}$")
    plt.plot(data["time"],data["slope"],color="b")
    plt.plot(data["time"],data["slope_spec"],color="r")
    plt.subplot(313)
    data["sigma_spec"]=sigma_spec
    plt.title("3$sigma$")
    plt.plot(data["time"],data["3sigma"],color="b")
    plt.plot(data["time"],data["sigma_spec"],color="r")
    return plt

if __name__ == "__main__":
    file = r"C:\Users\mayn\Desktop\ArrayBP\BPLack.xlsx"
    read_file = pd.read_excel(file)
    print(read_file.head())
    data = dataArrange(read_file,120)
    print(data.head())
    data["time"] = data["time"].astype(str)
    # data = timeTrans(data)
    # print(data.head())
    #输出清洗后数据
    file_path=r"C:\Users\mayn\Desktop\ArrayBP\new_data.xlsx"
    data.to_excel(file_path,sheet_name="data")
    multiChart(data,0.5)

 

index.html



  
    
    
    
    
    CTC Array FAB H3PO4监控系统

    
    

    
    
    
  
  

    

欢迎使用CTC Array FAB H3PO4监控系统,首先进行您的数据配置

{% csrf_token %}
原始文件路径
输出文件路径
group笔数
sigma_spec

 

 

bplack.html



  
    
    
    
    
    CTC Array FAB H3PO4监控系统

    
    

    
    
    
  
  

  

欢迎使用CTC Array FAB H3PO4监控系统, 本案技术支持人员:

No Dept. Name Tele email
1 QA/QS 王玉 12345 [email protected]
2 CF/INSP 路XX 12345 [email protected]
{% if cnt >= 1 %}

连续3笔数据mean(y2-y1)<0笔数: {{ cnt }}  最近一笔发生时间: {{ temp_time.0 }}  H3PO4值为: {{ temp_H3PO4.0 }}  请立即确认是否有异常!

{% endif %}

 

你可能感兴趣的:(Python,django,html)