-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraph.py
197 lines (171 loc) · 6.46 KB
/
graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 12:17:07 2020
@author: lekha
"""
import json
import random
import webbrowser
import pandas as pd
from bokeh.io import show, output_file
import matplotlib.pyplot as plt
from bokeh.plotting import figure
from flask import Flask, request, make_response
from flask_cors import CORS
from bokeh.models.annotations import Title
from bokeh.layouts import gridplot
from bokeh.embed import components
from sklearn import preprocessing
import base64
from io import BytesIO
import seaborn as sn
import numpy as np
from bokeh.models import Label
#Global data
global data
global graph
#Other Functions
#Function to generate random colours
def hexColour():
r = lambda: random.randint(0,255)
s='#%02X%02X%02X' % (r(),r(),r())
return s
#Function to create file head and send it to front end
def fileHead(df):
df=df.fillna("null")
displayData=df.values.tolist()[0:5]
metadata=list(df.columns)
responseData={"data":displayData,"metaData":metadata}
responseData=json.dumps(responseData,ensure_ascii=True,allow_nan=True)
return responseData
def organizePlots(l):
colslist=[]
rowslist=[]
k=0
for x in l:
if k%2==0:
if len(rowslist) !=0:
colslist.append(rowslist)
rowslist=[]
rowslist.append(x)
k=k+1
colslist.append(rowslist)
return colslist
#Flask Code
app = Flask(__name__)
CORS(app)
@app.route('/trainHead', methods=['GET'])
def trainHead():
global data
return fileHead(data)
#Function to set graph data
@app.route('/loadGraphData',methods=['POST'])
def loadGraphData():
global data
graphData=request.json['graphData']
graphMetaData=request.json['graphMetaData']
data=pd.DataFrame(graphData,columns=graphMetaData)
#print(data)
return "Yes"
#Function to return columns
@app.route('/getAttributes',methods=['GET'])
def graphType():
global data
global graph
y_attr=list(data.columns)
x_attr=list(data.columns)
x_attr.pop()
responseData={"X":x_attr,"Y":y_attr}
responseData=json.dumps(responseData,ensure_ascii=True,allow_nan=True)
r = make_response(responseData)
r.mimetype = 'text/plain'
return r
#Function to recieve attributes and plot graph
@app.route('/plotGraph',methods=['POST'])
def plotGraph():
global data
global graph
graph = request.form['graph']
y_attr=request.form['y_attr']
x_attr=request.form['x_attr']
x_attr=x_attr.split(',')
mapping=""
html = '<html><head></head><script src="js/importCommonFiles.js" type="text/javascript"></script><script src="https://cdn.bokeh.org/bokeh/release/bokeh-1.4.0.min.js" crossorigin="anonymous"></script>'
html += ' <script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-1.4.0.min.js" crossorigin="anonymous"></script> '
html += '<script src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-1.4.0.min.js"crossorigin="anonymous"></script>'
if y_attr!="None":
yattr = data[y_attr]
if(str(data[y_attr].dtype)=="object"):
le = preprocessing.LabelEncoder()
yattr=le.fit_transform(data[[y_attr]])
le_name_mapping = dict(zip(le.classes_, le.transform(le.classes_)))
mapping+="\n<b>Note : </b>The Y attribute values have been label encoded.</br><b>MAPPING:</b>"
for x in le_name_mapping:
mapping+="</br>"+x+":"+str(le_name_mapping[x])
if graph=="bar":
p = figure(plot_width=600, plot_height=600)
xlabel=""
for x in x_attr:
p.vbar(x=data[x], width=1.5, bottom=0,top=yattr,color=hexColour(),legend=x)
xlabel+=x
xlabel += " "
p.xaxis.axis_label =xlabel
p.yaxis.axis_label = y_attr
t = Title()
t.text = "graph:" + graph + " x:" + xlabel
p.title = t
script, div = components(p)
html+='<body><div class="container"><div class="row"><div class="col-5">'+ div +'</div><div class="col-2"></div><div class="col-5">'+mapping+'</div></div></div>'+script +'</body></html>'
with open('Web Pages\plottedGraph.html', 'w') as f:
f.write(html)
webbrowser.open_new_tab('Web Pages\plottedGraph.html')
return "SUCCESS"
if graph=="scatter":
p = figure(plot_width=600, plot_height=600)
for x in x_attr:
p.scatter(data[x], yattr, marker="x",line_color=hexColour(), fill_color=hexColour(), fill_alpha=0.5, size=12,legend=x)
t = Title()
t.text = "graph:" + graph + " x:" + ' '.join(x_attr)
p.title = t
script, div = components(p)
html += '<body><div class="container"><div class="row"><div class="col-5">' + div + '</div><div class="col-2"></div><div class="col-5">' + mapping + '</div></div></div>' + script + '</body></html>'
with open('Web Pages\plottedGraph.html', 'w') as f:
f.write(html)
webbrowser.open_new_tab('Web Pages\plottedGraph.html')
return "SUCCESS"
if graph=="line":
l=[]
xlabel=""
for x in x_attr:
p = figure(plot_width=600, plot_height=600)
p.line(data[x],yattr,color=hexColour(),legend=x)
p.xaxis.axis_label =x
p.yaxis.axis_label = y_attr
t=Title()
t.text ="graph:"+graph+" x:"+x
p.title = t
l.append(p)
script, divs = components(l)
scatterPlot = ""
for div in divs:
scatterPlot += '<div class="row"><div class="col-5">' + div + '</div><div class="col-2"></div><div class="col-5">' + mapping + '</div></div></br>'
html += '<body><div class="container">'+scatterPlot+ script + '</body></html>'
with open('Web Pages\plottedGraph.html', 'w') as f:
f.write(html)
webbrowser.open_new_tab('Web Pages\plottedGraph.html')
return "SUCCESS"
if graph=="correlation":
plt.figure(figsize=(12, 18))
ax=sn.heatmap(data.corr(), square=True, cmap='RdYlGn')
plt.subplots_adjust(bottom=0.30)
fig=ax.get_figure()
tmpfile = BytesIO()
plt.savefig(tmpfile, format='png')
encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8')
html = '<html><body>'+ '<img src=\'data:image/png;base64,{}\'>'.format(encoded) + '</body></html>'
with open('Web Pages\plottedGraph.html', 'w') as f:
f.write(html)
webbrowser.open_new_tab('Web Pages\plottedGraph.html')
return "SUCCESS"
def runGraphServer():
app.run(host='127.0.0.1', port= 5001)