def analyzer(): text = request.form['text'] avg_polarity = 0.175 avg_subjectivity = 0.444 blob = TextBlob(text) words = blob.words sentences = blob.sentences num_words = len(words) num_sentences = len(sentences) pol_base = blob.sentiment.polarity subj_base = blob.sentiment.subjectivity pol_vs_avg = pol_base - avg_polarity subj_vs_avg = subj_base - avg_subjectivity print 'Word Count: ', num_words print 'Sentence Count: ', num_sentences print 'Baseline Polarity: ', pol_base print 'Polarity versus average press release: ', pol_vs_avg print 'Baseline Subjectivity: ', subj_base print 'Subjectivity versus average press release: ', subj_vs_avg graph_url = make_plot(pol_base, subj_base) graph_html = tls.get_embed(graph_url) graph_html = Markup(graph_html) return render_template('index.html', graph_html=graph_html, num_words=num_words, num_sentences=num_sentences)
def make_histogram(layers,labels,name,xAxis,yAxis): data = [] for i in range(0,len(layers)): trace = go.Histogram( x=layers[i], name=labels[i], opacity=0.75 ) data.append(trace) layout = go.Layout( barmode='overlay', title=name, height=350, margin=dict( t=50, b=100, l=10, r=10, pad=30, ), xaxis=dict( title=xAxis ), yaxis=dict( title=yAxis ) ) name = getChartName.ts() fig = go.Figure(data=data, layout=layout) plot_url = py.plot(fig, filename=name,auto_open=False) embedInfo = tls.get_embed(plot_url) embedInfo = plotly_height_changer(embedInfo,300) return(embedInfo)
def makeGraph(username, bills): # Add data month = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ] # Create and style traces points = go.Scatter(x=month, y=bills, name="Bill", line=dict(color=("rgb(0, 153, 0)"), width=4)) data = [points] # Edit the layout layout = dict(title="Yearly Electric Bills", xaxis=dict(title="Month"), yaxis=dict(title="Money Spent")) # Plot and embed in ipython notebook! fn = username + "/year" plot_url = py.plot(data, filename=fn, auto_open=False) return tls.get_embed(plot_url)
def visualization(request): from device.models import Device from django.db.models import Count counts = [((val["type_of_device"], val["type_of_device__count"])) for val in Device.objects.values("type_of_device").annotate(Count("type_of_device"))] r = get_plots(counts) import plotly.tools as tls bar = tls.get_embed(r) return render(request, 'visual.html', {"type": bar })
def create(chartTitle, xTitle, yTitle, data, filename, shapes, minX, maxX, minY, maxY): signIn.auth() if(shapes==None): layout = dict(title = chartTitle, plot_bgcolor=chartConfigs._chartBgColor, paper_bgcolor=chartConfigs._chartBgColor, xaxis = dict(title = xTitle, gridcolor=chartConfigs._gridColor), yaxis = dict(title = yTitle, gridcolor=chartConfigs._gridColor), legend=dict(x=0.9,y=1,bgcolor=chartConfigs._chartBgColor), margin=dict(t=chartConfigs_topMargin, b=chartConfigs_bottomMargin, l=chartConfigs_leftMargin, r=chartConfigs_rightMargin, pad=chartConfigs_padding, color=chartConfigs._marginColor) ) else: layout = dict(title = chartTitle, plot_bgcolor=chartConfigs._chartBgColor, paper_bgcolor=chartConfigs._chartBgColor, font=dict(color=chartConfigs._titleColor), xaxis = dict(title = xTitle, ticks="inside", tickfont=dict(color=chartConfigs._tickColor), titlefont=dict(color=chartConfigs._tickColor), tickcolor=chartConfigs._tickColor, range=[minX,maxX], gridcolor=chartConfigs._gridColor, linecolor=chartConfigs._lineColor, linewidth=chartConfigs._lineWidth, zerolinecolor=chartConfigs._zeroLineColor, zerolinewidth=chartConfigs._lineWidth), yaxis = dict(title = yTitle, ticks="inside", tickfont=dict(color=chartConfigs._tickColor), titlefont=dict(color=chartConfigs._tickColor), tickcolor=chartConfigs._tickColor, range=[minY,maxY], gridcolor=chartConfigs._gridColor, linecolor=chartConfigs._lineColor, linewidth=chartConfigs._lineWidth, zerolinecolor=chartConfigs._zeroLineColor, zerolinewidth=chartConfigs._lineWidth), shapes=shapes, legend=dict(x=0.88,y=1,bgcolor=chartConfigs._chartBgColor,font=dict(color=chartConfigs._legendColor)) ) fig = dict(data=data, layout=layout) plot_url = py.plot(fig, filename=filename, auto_open=False) embedInfo = tls.get_embed(plot_url) return(embedInfo)
def createGraph(data): traces = [] releaseDates = [] rtScores = [] metaScores = [] titles = [] for film in data['Films']: film[3] = dateScore(film[3]) data['Films'].sort(key=lambda x: x[3]) for film in data['Films']: if 'N/A' in film: continue titles.append(film[0]) rtScores.append(film[1]) metaScores.append(film[2]) releaseDates.append(film[3]) traces.append(go.Scatter( x = releaseDates, y = rtScores, mode = "lines+markers", name = 'Tomatoscore', text = titles )) traces.append(go.Scatter( x = releaseDates, y = metaScores, mode = "lines+markers", name = 'Metascore', text = titles )) layout = go.Layout( title = data['Person'] + ": " + data['Type'], xaxis = { 'title': 'Date of Release' }, yaxis = { 'title': 'Rating' } ) figure = go.Figure(data=traces, layout=layout) plot_url = py.plot(figure, filename='Filmography', auto_open=False) return tls.get_embed(plot_url)
def get_bargraph_gender(): """ Rendering sex distribution bar graph from the clients.csv file using plotly """ values = get_sexes_list() data = [ go.Bar( x=['Male','Female','Not Specified'], y=[values['M'],values['F'],values['N']] ) ] plot_url = py.plot(data, filename='Gender Bar Char',auto_open=False) return tls.get_embed(plot_url)
def get_piegraph_gender(): """ Rendering sex distribution pie chart from the clients.csv file using plotly """ gender = get_sexes_list() fig = { 'data': [{'labels': ['Male', 'Female', 'Not Specified'], 'values': [gender['M'],gender['F'],gender['N']], 'type': 'pie'}], 'layout': {'title': 'Gender Distribution From Clients File'} } url = py.plot(fig, filename='Gender Pie Chart', auto_open=False) return tls.get_embed(url)
def plotly_pipe(data, plt_type): name = hashlib.sha224(datetime.datetime.now() .isoformat().encode('utf-8')).hexdigest() + '.png' # plt.image.save_as(data, name, width=1280, height=760) url = plt.plot(data, validate=False, filename=datetime.date.today().isoformat() + ' Trello task history', auto_open=False) # print(url) composed_url = '{url}.{im}?width={w}&height={h}'.format(url=url, im='png', w=1280, h=760) with open(name, 'wb') as f: f.write(requests.get(composed_url).content) embed = tls.get_embed(url) s3.Bucket('wg-plots').put_object(Key=datetime.date.today().isoformat() + '-' + plt_type + '.html', Body=embed, ContentType='text/html') url = 'https://s3.amazonaws.com/wg-plots/{}-{}.html'.format(datetime.date.today().isoformat(), plt_type) link = upload_image(name) remove(name) return (link['link'], url)
def test_get_embed_url_with_share_key(self): # Check the embed url for url with share_key included get_embed_return = tls.get_embed('https://plot.ly/~neda/6572' + '?share_key=AH4MyPlyDyDWYA2cM2kj2m') expected_get_embed = ("<iframe id=\"igraph\" scrolling=\"no\" " "style=\"border:none;\" seamless=\"seamless\" " "src=\"{plotly_rest_url}/" "~{file_owner}/{file_id}.embed?" "share_key={share_key}\" " "height=\"{iframe_height}\" " "width=\"{iframe_width}\">" "</iframe>").format(plotly_rest_url="https://" + "plot.ly", file_owner="neda", file_id="6572", share_key="AH4MyPlyDyDWYA2" + "cM2kj2m", iframe_height=525, iframe_width="100%") self.assertEqual(get_embed_return, expected_get_embed)
def make_line_chart(layers,labels,name,xAxis,yAxis): data = [] for i in range(0,len(layers)): trace = go.Scatter( x = list(range(1,len(layers[i]))), name = labels[i], y = layers[i] ) data.append(trace) layout = go.Layout( barmode='overlay', title=name, xaxis=dict( title=xAxis ), yaxis=dict( title=yAxis ) ) fig = go.Figure(data=data, layout=layout) plot_url = py.plot(fig, filename=name,auto_open=False) embedInfo = tls.get_embed(plot_url) return(embedInfo)
def teams_output(): #totry = np.arange(0,130,1) team1_png = request.args.get('team1') if team1_png is None: team1_png = 'Ohio_State_Buckeyes' team1 = team1_png.replace('_', ' ') team2_png = request.args.get('team2') if team2_png is None: team2_png = 'Michigan_State_Spartans' team2 = team2_png.replace('_', ' ') win_dict = base_model(team1, team2) winprob = win_dict['prob'] if winprob <= 0.5: winprob = int(round((1.0-winprob)*100.0)) teamwin=team2_png winner = team2 keys = win_dict['keys'] else: winprob = int(round((winprob*100.0))) teamwin=team1_png winner = team1 keys = win_dict['keys'] myplot = tls.get_embed(win_dict['url']) myplot = myplot.replace('525', '380') myplot = myplot.replace('100%', '55%') return render_template("output.html", team1_png=team1_png, team2_png=team2_png, teamwin=teamwin, winner=winner, myplot=myplot, winprob=winprob, key1=keys[0],key2=keys[1],key3=keys[2])
def make_chart(fig): signIn.auth() filename = getChartName.ts() plot_url = py.plot(fig, filename=filename, auto_open=False) embedInfo = tls.get_embed(plot_url) return(embedInfo)
def make_candlestick(gamelog, column, reduce_func=None): base_series = gamelog.set_index("Date")[column] if reduce_func: series = reduce_func(base_series).dropna() else: series = base_series.cumsum().dropna() weekdata = list(create_weekly(series)) weeks = pd.DataFrame(weekdata).dropna() fig = FF.create_candlestick(weeks.Open, weeks.High, weeks.Low, weeks.Close, dates=weeks.start_date) fig['layout'].update(height=600, width=600, title=column) return fig badEggRe = re.compile(r"(\([0-9]+\))") cleanEgg = (lambda val: None if isinstance(val, float) else ("2016 " + badEggRe.sub("", str(val)))) gamelog = get_gamelog_cached().dropna() gamelog.Date = gamelog.Date.apply(cleanEgg) gamelog.Date = pd.to_datetime(gamelog.Date) wpa_trace = make_candlestick(gamelog, "WPA") obp_trace = make_candlestick(gamelog, "OBP", reduce_func=pd.expanding_mean) traces = [wpa_trace, obp_trace] html = "" for i in range(len(traces)): trace = traces[i] url = plotly.plot(trace, filename='murphy-candlestick-{}'.format(i), auto_open=True) html += get_embed(url) with open("index.html", "w") as fobj: fobj.write(html)
def plotly_embed(url): # TODO: Re-implement get_embed to use the template system. get_embed should be safe, but using # mark_safe is always a vulnerability. return mark_safe(tls.get_embed(url))
def test_get_invalid_embed(): url = 'https://plot.ly/~PlotBot/a/' tls.get_embed(url)
def test_get_valid_embed(): url = 'https://plot.ly/~PlotBot/82/' embed = tls.get_embed(url)
def makeGraph(username, etc, goal, limit): # Add data now = datetime.datetime.now() days = [1] if now.month == "January" or now.month == "March" or now.month == "May" or now.month == "July" or now.month == "August" or now.month == "October" or now.month == "December": days = [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] elif now.month == "April" or now.month == "June" or now.month == "September" or now.month == "November": days = [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] elif (now.year % 4) == 0: days = [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] else: days = [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] goals=[] for i in days: goals.append(goal) limits=[] for i in days: limits.append(limit) # Create and style traces points = go.Scatter( x = days, y = etc, name = 'Bill', line = dict( color = ('rgb(0, 153, 0)'), width = 4) ) gls = go.Scatter( x = days, y = goals, name = 'Goal', line = dict( color = ('rgb(0, 0, 0)'), width = 4, dash = 'dot') ) lmts = go.Scatter( x = days, y = limits, name = 'Limit', line = dict( color = ('rgb(0, 0, 0)'), width = 4, dash = 'dot') ) data = [points, gls, lmts] # Edit the layout layout = dict(title = 'Daily Electric Estimates', xaxis = dict(title = 'Days'), yaxis = dict(title = 'Estimated Money Spent'), ) # Plot and embed in ipython notebook! fn = username+"/"+str(now.month) plot_url = py.plot(data, filename=fn, auto_open=False) return tls.get_embed(plot_url)
def maju_cantik_mundur_cantik(calculID,freq,rhoa,phas,maxiter_depth=10,maxiter_rho=50,convcrit=0,demo=False): """ Zohdy reborn """ from IPython.display import clear_output,display import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import time,sys from copy import deepcopy import plotly.plotly as py import plotly.graph_objs as go import plotly.tools as tls from plotly import tools # sign-in to plot.ly server py.sign_in('irnaka','jqqy1w0m86') ts = 0.01 if demo else 0. rhoi = np.zeros((len(freq))) dhi = np.zeros((len(freq))) for i in range(len(freq)): rhoi[i] = rhoa[i]*((np.pi/(2.*phas[i])-1.)) dhi[i] = np.sqrt(rhoa[i]*1./freq[i]/2./np.pi/(4.*np.pi*1e-7)) rhoi = np.abs(rhoi) tebal = np.diff(dhi)*1.2 f0,rh0,ph0 = mt_maju_rekursi(freq,rhoi,tebal) print 'initial model done!' # perbaikan gizi ke arah depth eror = [] erorpha = [] erorrho = [] for i in range(maxiter_depth): tebal = tebal*0.9 f0,rh0,ph0 = mt_maju_rekursi(freq,rhoi,tebal) erorrho.append(np.sum((np.log(rhoa)-np.log(rh0))**2)) erorpha.append(np.sum(np.log(phas/ph0))**2) if convcrit==0: eror.append((erorrho[-1]+erorpha[-1])/2.) elif convcrit==1: eror.append(erorrho[-1]) elif convcrit==2: eror.append(erorpha[-1]) if len(eror)>1 and eror[-1]>eror[-2]: print('Depth convergence has been reached!') tebal = tebal/0.9 f0,rh0,ph0 = mt_maju_rekursi(freq,rhoi,tebal) iterdepth = i-1 eror.pop(-1) erorpha.pop(-1) erorrho.pop(-1) break if i==maxiter_depth-1: iterdepth = i # perbaikan gizi ke arah rho fr = [];r = [];p = [];l = [];er = [];ri =[] for i in range(maxiter_rho): print 'rhoi\n',rhoi for j in range(len(freq)): rhotemp = deepcopy(rhoi) if np.log(rh0[j])>0.: rhoi[j] = rhoi[j]* (np.log(rhoa[j])/np.log(rh0[j])) else: rhoi[j] = rhoi[j]* (np.log(rhoa[j])-np.log(rh0[j])) f0,rh0,ph0 = mt_maju_rekursi(freq,rhoi,tebal) if i==0: f0old = deepcopy(f0) rh0old = deepcopy(rh0) ph0old = deepcopy(ph0) rhoiold = deepcopy(rhoi) erorrho.append(np.sum((np.log(rhoa)-np.log(rh0))**2)) erorpha.append(np.sum(np.log(phas/ph0))**2) if convcrit==0: eror.append((erorrho[-1]+erorpha[-1])/2.) elif convcrit==1: eror.append(erorrho[-1]) elif convcrit==2: eror.append(erorpha[-1]) if eror[-1]>eror[-2] and eror[-3]>eror[-2]: fr.append(f0old) r.append(rh0old) p.append(ph0old) ri.append(rhoiold) er.append(eror[-2]) l.append(len(eror)-2) #if len(l)==3: # break if i==maxiter_rho-1: fr.append(f0old) r.append(rh0old) p.append(ph0old) ri.append(rhoiold) er.append(eror[-1]) l.append(len(eror)-1) rhoiold = deepcopy(rhoi) f0old = deepcopy(f0) rh0old = deepcopy(rh0) ph0old = deepcopy(ph0) # finding global minima rhl = deepcopy(rh0) phl = deepcopy(ph0) minIndex = er.index(min(er)) f0 = fr[minIndex] rh0 = r[minIndex] ph0 = p[minIndex] rhoi = ri[minIndex] # create the figure f = plt.figure(figsize=(16.,8.)) # plot rho apparent ax1 = f.add_subplot(2,3,(1,2)) ax1.plot(f0,rhl,'b',label='$\\rho_{app_{calc,it = %d}}$'%(maxiter_rho+iterdepth+1)) ax1.plot(freq,rhoa,'go',label='$\\rho_{app_{obs}}$') ax1.plot(f0,rh0,'r',label='$\\rho_{app_{calc,min_{global}}}$\n$\\epsilon = %.4f$'%(er[minIndex])) boundx = np.exp(0.01*(np.log(np.max(f0)/np.min(f0)))) ax1.set_xlim(np.exp(np.log(np.min(f0))-boundx),np.exp(np.log(np.max(f0))+boundx)) ax1.set_yscale('log') ax1.set_xscale('log') ax1.set_title('Apparent resistivity and Phase') ax1.set_ylabel('apparent resistivity ($\\rho_{app}$)') ax1.set_xlabel('frequency (Hz)') ax1.grid(True,which='both') ax1.legend(loc='upper left',fancybox=True,framealpha=0.4) # plot phase ax1t = ax1.twinx() ax1t.plot(f0,np.degrees(phl),'b--') ax1t.plot(f0,np.degrees(phas),'gx') ax1t.plot(f0,np.degrees(ph0),'r--',label='$\\theta_{app_{calc,min_{global}}}$') ax1t.set_ylabel('phase') ax1t.set_xlim(np.exp(np.log(np.min(f0))-boundx),np.exp(np.log(np.max(f0))+boundx)) ax1t.legend(loc='lower right',fancybox=True,framealpha=0.4) # plot iteration error ax2 = f.add_subplot(2,3,(4,5)) ax2.plot(np.arange(1,iterdepth+i+3),eror,'g',label='rho iter (mean)') ax2.plot(np.arange(1,iterdepth+2),eror[:iterdepth+1],'r',label='thick iter (mean)') ax2.plot(np.arange(1,iterdepth+i+3),erorrho,'g-.',label='rho iter ($\\rho_{app}$)') ax2.plot(np.arange(1,iterdepth+2),erorrho[:iterdepth+1],'r',label='thick iter ($\\rho_{app}$)') ax2.plot(np.arange(1,iterdepth+i+3),erorpha,'g--',label='rho iter ($\\theta$)') ax2.plot(np.arange(1,iterdepth+2),erorpha[:iterdepth+1],'r--',label='thick iter ($\\theta$)') ax2.scatter(l[minIndex]+1,er[minIndex],s=400,c='blue',marker=(5, 2),label='global minima ($\\rho_{app}$)') ax2.set_xlim(1,maxiter_rho+iterdepth) ax2.set_xlabel('iteration') ax2.set_ylabel('error') ax2.grid(True,which='both') ax2.set_yscale('log') ax2.legend(loc='best',fancybox=True,framealpha=0.4) # plot depth profile resist,kedalaman = gambar_model(rhoi,tebal) ax3 = f.add_subplot(2,3,(3,6)) ax3.plot(resist,kedalaman) ax3.set_xscale('log') ax3.set_ylabel('depth (m)') ax3.set_xlabel('resistivity ($\\rho$)') ax3.grid(True,which='both') ax3.set_ylim(kedalaman[0],kedalaman[-1]) ax3.invert_yaxis() # deleting old data basedir = '/media/serverdisk//MTZohdy' remove_trash(basedir) # export the figure plt.tight_layout() plt.savefig(basedir+'/images/out'+calculID+'.png') # export numeric data np.savetxt(basedir+'/outputs/data_'+calculID+'.txt',(freq,rhoa,rh0,phas,ph0),fmt='%1.5e') np.savetxt(basedir+'/outputs/iter_'+calculID+'.txt',(np.arange(1,iterdepth+i+3),eror,erorrho,erorpha),fmt='%1.5e') np.savetxt(basedir+'/outputs/out_'+calculID+'.txt',(resist,kedalaman),fmt='%1.5e') # converting to plot.ly figure """ trace1 = go.Scatter(x = f0,y = rhl, mode='lines', name='calc $\\rho_{app}$,last iter', xaxis = 'x1', yaxis = 'y1') trace2 = go.Scatter(x = freq,y = rhoa, mode='markers', name='obs $\\rho_{app}$', xaxis = 'x1', yaxis = 'y1') trace3 = go.Scatter(x = f0,y = rh0, mode='lines', name='calc $\\rho_{app}$,$min_{glob}$', xaxis = 'x1', yaxis = 'y1') trace4 = go.Scatter(x = f0,y = np.degrees(phl), mode='lines', name='calc $\\theta$,last iter', xaxis = 'x1', yaxis = 'y2') trace5 = go.Scatter(x = freq,y = np.degrees(phas), mode='markers', name='obs $\\theta$', xaxis = 'x1', yaxis = 'y2') trace6 = go.Scatter(x = f0,y = np.degrees(ph0), mode='lines', name='calc $\\theta$,$min_{glob}$', xaxis = 'x1', yaxis = 'y2') trace7 = go.Scatter(x = np.arange(1,iterdepth+maxiter_rho+3), y = eror, mode='lines', marker = dict( line = dict( color = 'rgb(0,255,0)' )), name = '$\\rho_{app}$ iter rho', xaxis = 'x3', yaxis = 'y3') trace8 = go.Scatter(x = np.arange(1,iterdepth+2), y = eror[:iterdepth+1], mode='lines', marker = dict( line = dict( color = 'rgb(255,0,0)' )), name = '$\\rho_{app}$ iter thickness', xaxis = 'x3', yaxis = 'y3') trace9 = go.Scatter(x = np.arange(1,iterdepth+maxiter_rho+3), y = erorpha, mode='lines', marker = dict( line = dict( color = 'rgb(0,255,0)' )), name = '$\\theta$ iter rho', xaxis = 'x3', yaxis = 'y3') trace10 = go.Scatter(x = np.arange(1,iterdepth+2), y = erorpha[:iterdepth+1], mode='lines', marker = dict( line = dict( color = 'rgb(255,0,0)' )), name = '$\\theta$ iter thickness', xaxis = 'x3', yaxis = 'y3') trace11 = go.Scatter(x = resist,y = kedalaman, mode = 'lines', xaxis = 'x4', yaxis = 'y4') data = [trace1,trace2,trace3,trace4,trace5,trace6,trace7,trace8,trace9,trace10,trace11] layout = go.Layout( yaxis = dict( title = 'Apparent Resistivity', domain = [0.55,1.0], type = 'log' ), yaxis2 = dict( title = 'Phase', domain = [0.55,1.0], overlaying = 'y', side = 'right' ), yaxis3 = dict( title = 'Error', domain = [0.0,0.45], type = 'log' ), xaxis = dict( title = 'Frequency (Hz)', domain = [0.0,0.45], type = 'log' ), xaxis3 = dict( title = 'Number iteration', domain = [0.0,0.45], anchor = 'y3' ), xaxis4 = dict( title = 'Resistivity', domain = [0.55,1.0], type = 'log' ), yaxis4 = dict( title = 'Depth', domain = [0.55,1.0], anchor = 'x4', autorange = 'reversed' ), showlegend=False ) fig = go.Figure(data=data,layout=layout) """ resist,kedalaman = gambar_model(rhoi,tebal) trace1 = go.Scatter(x = f0,y = rhl, mode='lines', name='rho app on last iteration') trace2 = go.Scatter(x = freq,y = rhoa, mode='markers', name='rho app observed') trace3 = go.Scatter(x = f0,y = rh0, mode='lines', name='rho app on global minimum') trace4 = go.Scatter(x = f0,y = np.degrees(phl), mode='lines', name='theta on last iteration') trace5 = go.Scatter(x = freq,y = np.degrees(phas), mode='markers', name='theta observed') trace6 = go.Scatter(x = f0,y = np.degrees(ph0), mode='lines', name='theta calc global minimum') trace7 = go.Scatter(x = np.arange(1,iterdepth+maxiter_rho+3), y = eror, mode='lines', marker = dict( line = dict( color = 'rgb(0,255,0)' )), name = 'mean on rho iteartion') trace8 = go.Scatter(x = np.arange(1,iterdepth+2), y = eror[:iterdepth+1], mode='lines', marker = dict( line = dict( color = 'rgb(255,0,0)' )), name = 'mean on thickness iteration') trace9 = go.Scatter(x = np.arange(1,iterdepth+maxiter_rho+3), y = erorpha, mode='lines', marker = dict( line = dict( color = 'rgb(0,255,0)' )), name = 'phase on rho iteration') trace10 = go.Scatter(x = np.arange(1,iterdepth+2), y = erorpha[:iterdepth+1], mode='lines', marker = dict( line = dict( color = 'rgb(255,0,0)' )), name = 'phase on thickness iteration') trace11 = go.Scatter(x = np.arange(1,iterdepth+maxiter_rho+3), y = erorrho, mode='lines', marker = dict( line = dict( color = 'rgb(0,255,0)' )), name = 'rho on rho iteration') trace12 = go.Scatter(x = np.arange(1,iterdepth+2), y = erorrho[:iterdepth+1], mode='lines', marker = dict( line = dict( color = 'rgb(255,0,0)' )), name = 'rho on thickness iteration') trace13 = go.Scatter(x = l[minIndex]+1, y = er[minIndex], mode = 'markers', name = 'global minima') trace14 = go.Scatter(x = resist,y = kedalaman, mode = 'lines', name = 'depth vs resistivity') fig = tools.make_subplots(rows=3, cols=2, specs=[[{},{'rowspan':3}], [{},None], [{},None]], print_grid = True) fig.append_trace(trace1,1,1) fig.append_trace(trace2,1,1) fig.append_trace(trace3,1,1) fig.append_trace(trace4,2,1) fig.append_trace(trace5,2,1) fig.append_trace(trace6,2,1) fig.append_trace(trace7,3,1) fig.append_trace(trace8,3,1) fig.append_trace(trace9,3,1) fig.append_trace(trace10,3,1) fig.append_trace(trace11,3,1) fig.append_trace(trace12,3,1) fig.append_trace(trace13,3,1) fig.append_trace(trace14,1,2) fig['layout']['xaxis1'].update(title='Frequency (Hz)', type='log') fig['layout']['xaxis3'].update(title='Frequency (Hz)', type='log') fig['layout']['xaxis4'].update(title='Number of Iteration') fig['layout']['xaxis2'].update(title='Resistivity', type='log') fig['layout']['yaxis1'].update(title='Apparent Resistivity', type='log') fig['layout']['yaxis3'].update(title='Phase') fig['layout']['yaxis4'].update(title='Error', type='log') fig['layout']['yaxis2'].update(title='Depth (m)', autorange='reversed') fig['layout'].update(title='inversion result', showlegend=False) try: plot_url_freq_rho_phase = py.plot(fig,filename='MTZohdy_output',auto_open=False) print tls.get_embed(plot_url_freq_rho_phase) plotly_success = True except Exception: plotly_success = False return f0,rh0,ph0,rhoi,tebal,plotly_success
def longitudes_and_latitudes_graph(rows): station_dict = {} trip_dict = {} max_counter = 1 for row in rows: station_dict[row['Starting Station ID']] = ( row['Starting Station Latitude'], row['Starting Station Longitude']) key = (row['Starting Station ID'], row['Ending Station ID']) if key not in trip_dict: trip_dict[key] = [ row['Starting Station Latitude'], row['Starting Station Longitude'], row['Ending Station Latitude'], row['Ending Station Longitude'], 0 ] # "+=1" for the counter i.e 0 trip_dict[key][4] += 1 max_counter = max(max_counter, trip_dict[key][4]) layout = dict( title='Bike Share Paths', showlegend=False, geo=dict( scope='usa', projection=dict(type='azimuthal equal area'), showland=True, landcolor='rgb(243, 243, 243)', countrycolor='rgb(204, 204, 204)', ), ) stations = [ dict( type='scattergeo', locationmode='USA-states', lon=[v[1] for k, v in station_dict.items()], lat=[v[0] for k, v in station_dict.items()], hoverinfo='text', # Will show Station ID on hover text=[k for k, v in station_dict.items()], mode='markers', marker=dict(size=2, color='rgb(255, 0, 0)', line=dict(width=3, color='rgba(68, 68, 68, 0)'))) ] # t is reffering to the built-in "sorted" tuple trip_dict = sorted(trip_dict.items(), key=(lambda t: -t[1][4])) bike_share_paths = [] for (key, (st_lat, st_lon, end_lat, end_lon, counter)) in trip_dict[:50]: bike_share_paths.append( dict( type='scattergeo', locationmode='USA-states', lon=[st_lon, end_lon], lat=[st_lat, end_lat], mode='lines', line=dict( width=1, color='red', ), opacity=float(counter) / float(max_counter), )) # import pdb; pdb.set_trace() fig = go.Figure(data=stations + bike_share_paths, layout=layout) ply.sign_in('pnoonan32', open("PlotlyAPI.txt").read().strip()) url = ply.plot(fig, auto_open=False) print(url) open("Bike-Share-Trip-Path.html", "w").write("<h1>My cool graph</h1>" + tls.get_embed(url))