Data visualization analysis (bar charts, pie charts, line charts, radar charts)

Analysis files 'course grades .xlsx', at least to complete the content:

1) different class average cases per year

2) different years overall grade point average case

3) gender student achievement situation, and the results were analyzed to show the contents of the three with the appropriate chart.

 

Importing the library

from functools import reduce
import xlrd
from flask import Flask, jsonify, render_template, request, url_for
from pyecharts import Line,Bar,Pie,Radar

 

python read excel file data

= excel_path " .. \\ class.xlsx " 
    # open the file, obtain workbook excel file (workbook) objects 
    Excel = xlrd.open_workbook (excel_path, encoding_override = " UTF-. 8 " )
     # returns all objects Sheet List 
    all_sheet = excel.sheets ()
     # loop through all of the data sheet for each table object is stored 
    grade_list = []
     # the data file stored into grade_list 
    for sheet in all_sheet:
         for each_row in Range (sheet.nrows): # cycles per print line 
            # each_row = "". join (str (each_row) .split ())
            grade_list.append(sheet.row_values(each_row))
   

 

python chart Chinese garbled

# Set Chinese distortion 
from pylab Import * 
mpl.rcParams [ ' font.sans serif- ' ] = [ ' SimHei ' ]

 

The addition averaging list data

    def sum_list(items):
        sum_numbers = 0
        count = 0
        for x in items:
            sum_numbers += x
            count += 1
        return int(sum_numbers / count)

 

Find a different grade classes all data

# Find all the data classes of different grades 
    DEF deffentScore (Grade):
         # Different grades corresponding data 
        grade_score = []
         for grade_list_row in grade_list:
             IF Grade in grade_list_row [0]: 
                grade_score.append (grade_list_row) 
        return grade_score
     # find different grades class 
    DEF deffentGrade (Grade):
         # different grades corresponding classification 
        grade_score = []
         for grade_list_row in grade_list:
             IF Grade in grade_list_row [0]and grade_list_row[0] not in grade_score:
                grade_score.append(grade_list_row[0])
        return grade_score
 

FIG prepared using a map and reduce str2float function, converted into the floating-point number to a string

Using a map and reduce str2float write function, the string '123.456' into float 123.456
 DEF StrToFloat (S): 
    L = s.split ( ' . ' )
     Return reduce ( the lambda X, Y: int (X) + int (y) / 10 ** len ( y), l)

 

python list remove empty data

# Remove null data, data is absent, the spaces in the table is removed 
    DEF removeNull (alist):
         for I in alist:
             IF  ' absent '  in I [. 4] or  ''  in I: 
                alist.remove (I) 
        clist = []
         for I in alist: 
            for blist = [] 
            COUNT = 0
             for Y in I: 
                Y = '' .join (STR (Y) .split ()) 
                COUNT+=1
                if count>2 and count<6:
                    if '.'in y:
                        y=StrToFloat(y)
                    else:
                        y=int(y)
                blist.append(y)
            clist.append(blist)
        return clist

 

Use flask frame, and acquires data from the front page, the process returns back page

 
 
from flask import Flask, jsonify, render_template, request, url_for

app = Flask(__name__)

def main():
@app.route("/index")
def index():
overAll()
overAllTwo()
return render_template("Base.html")
@app.route('/test1',methods=['POST'])
def testGet1():
sex = request.form.get('sex')
sex1(str(sex))
print("执行get1")
return render_template("Base.html")

if __name__ == '__main__':
    main()
    app.run(host='127.0.0.1', port=8080, debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>课程分析</title>
</head>
<body>
    <div style="display: flex; flex-direction: column">
        <div>
            <form action="/test" method="post">
                <input type="text" name="year" >
                <input type="submit" value="提交" onclick="change(1)">
            </form>
            <br>
            <iframe src="http://127.0.0.1:8080/yearClass"
                    width="850px" height="400px"   frameborder="1/0"
                    name="" id="iframe-a" scrolling="no"></iframe>
        </div>
        <div>
            <iframe src="http://127.0.0.1:8080/overall"
                    width="850px" height="400px"   frameborder="1/0"
                    name="" id="iframe-b" scrolling="no"></iframe>
        </div>
        <div>
            <iframe src="http://127.0.0.1:8080/overalltwo"
                    width="850px" height="400px"   frameborder="1/0"
                    name="" id="iframe-c" scrolling="no"></iframe>
        </div>
        <div>
            <form action="/test1" method="post">
                <input type="text" name="sex" >
                <input type="submit" value="提交" onclick="change(2)">
            </form>
            <br>
            <iframe src="http://127.0.0.1:8080/sex"
                    width="850px" height="400px"   frameborder="1/0"
                    name="" id="iframe-d" scrolling="no"></iframe>
        </div>
    </div>
</body>
<script>

    function change(e) {
        if(e==1){
            document.getElementById('iframe-a').contentWindow.location.reload();
        }
        else if(e==2){
            document.getElementById('iframe-d').contentWindow.location.reload();
        }
    }
</script>
</html>

1, the use of the technology stack project

      flask Framework

      Numpy: Matrix calculation processing of data with most other base frame;

      Matplotlab: Professional drawing tools, word or saying really is inserted between Matlab plot of the word formation;

      PyEcharts: is a powerful data python with the binding echarts visualization tools, can show dynamic map, using the online reports more beautiful and easy to display data, hover over the FIG., The value can be displayed, and other labels.

2, the system module list

     Histograms, pie charts, line charts, radar FIG.

3, column: Every year a different class average case

 

app.route @ ( ' / Test ' , Methods = [ ' the POST ' ])
     DEF testGet (): 
        year = request.form.get ( ' year ' ) 
        year_score = deffentScore (year) 
        year_class = deffentGrade (year) 
        avg_score = differentClassesEachYear (year_class, year_score)
         # drawing 
        # // set the histogram of the main title and subtitle 
        bar = bar ( " histogram " , " every year different class average case " )
         #// Add the histogram data and configuration items 
        bar.add ( " GPA " , year_class, avg_score, mark_line = [ " Average " ], mark_point = [ " max " , " min " ])
         # @ generates a local file ( The default is .html file) 
        bar.render ( ' ./templates/yearClass.html ' )
         Print ( " execute GET " )
         return render_template ( " base.html " )

4, pie: an overall analysis of the situation based on the average scores in different years

def overAll():
        year=['2016','2017','2018']
        year=['16','17','18']
        year_score=[]
        for i in year:
            list1=[]
            for grade_list_row in grade_list:
                if i in grade_list_row[0]:
                    list1.append(grade_list_row[4])
            year_score.append(sum_list(list1))
        # //设置主标题与副标题,标题设置居中,设置宽度为900
        pie = Pie("饼状图", "不同年份总体平均成绩情况",title_pos='center',width=900)
        # //加入数据,设置坐标位置为【75,50】,上方的colums选项取消显示,显示label标签
        pie.add("年份", year, year_score ,center=[50,50],is_legend_show=False,is_label_show=True)
        # //保存图表
        pie.render('./templates/overall.html')

5、折线图

 

def overAllTwo():
        year_score=deffentScore('16')
        year_class=deffentGrade('16')
        avg_score=differentClassesEachYear(year_class,year_score)
        year_score1=deffentScore('17')
        year_class1=deffentGrade('17')
        avg_score1=differentClassesEachYear(year_class1,year_score1)
        year_score2=deffentScore('18')
        year_class2=deffentGrade('18')
        avg_score2=differentClassesEachYear(year_class2,year_score2)
        class1=['班级1','班级2','班级3']
        #移除最后一个元素
        avg_score2.pop()
        line = Line("折线图","不同年份总体平均成绩情况")
        # //is_label_show是设置上方数据是否显示
        line.add("2016年", class1, avg_score, is_label_show=True)
        line.add("2017年", class1, avg_score1, is_label_show=True)
        line.add("2018年", class1, avg_score2, is_label_show=True)
        line.render('./templates/overalltwo.html')

6、雷达图:根据不同性别学生分析成绩情况

def sex1(sexName):
        sex_score=[]
        sex_class=[]
        score=[]
        for grade_list_row in grade_list:
            if sexName in grade_list_row[1]:
                sex_score.append(grade_list_row)
        for grade_list_row in sex_score:
            if grade_list_row[0] not in sex_class:
                sex_class.append(grade_list_row[0])
        for className in sex_class:
            list1=[]
            for grade_list_row in sex_score:
                if className==grade_list_row[0]:
                    list1.append(grade_list_row[4])
            score.append(sum_list(list1))
        score1=[]
        score1.append(score)
        print(score1,sex_class)
        radar = Radar("雷达图", "不同班级男女的平均成绩")
        schema =[('网络1611',100), ('网络1612',100), ('网络1613',100),
                 ('网络1711',100), ('网络1712',100), ('网络1714',100),
                 ( '网络1811',100), ('网络1814',100), ('网络1813',100)]
        # //传入坐标
        radar.config(schema)
        # //一般默认为同一种颜色,这里为了便于区分,需要设置item的颜色
        radar.add("平均成绩",score1,item_color="#1C86EE")
        radar.render('./templates/sex.html')

Guess you like

Origin www.cnblogs.com/WT-01/p/12077895.html