def _plot_loading_pca_matrix(self, components_df, n_components): output_directory = os.path.join(self.scratch, str(uuid.uuid4())) self._mkdir_p(output_directory) result_file_paths = [] all_pairs = list(itertools.combinations(range(1, n_components + 1), 2)) for pair in all_pairs: first_component = pair[0] second_component = pair[1] result_file_path = os.path.join( output_directory, 'pca_loading_plot_{}_{}.html'.format(first_component, second_component)) traces = list() data = go.Data(traces) layout = go.Layout( xaxis=go.XAxis(title='PC{}'.format(first_component), showline=False), yaxis=go.YAxis(title='PC{}'.format(second_component), showline=False)) fig = go.Figure(data=data, layout=layout) coeff = list() coeff.append(components_df['principal_component_{}'.format( first_component)]) coeff.append(components_df['principal_component_{}'.format( second_component)]) coeff = np.transpose(coeff) loading_x = list() loading_y = list() loading_text = list() for idx, position in enumerate(coeff): loading_x.append(0) loading_y.append(0) loading_text.append('0') loading_x.append(position[0]) loading_y.append(position[1]) loading_text.append(components_df.index[idx]) fig.add_trace( go.Scatter(x=loading_x, y=loading_y, mode="lines+markers", name="loading plot", text=loading_text, textposition="bottom center")) plot(fig, filename=result_file_path) result_file_paths.append(result_file_path) return result_file_paths
def plot_word_frequency(word_list, plot_title): trace1 = {"x": list(word_list[0]), "y": list(word_list[1]), "type": "bar"} data = go.Data([trace1]) layout = {"title": plot_title, "yaxis": {"title": "Frequency"}} fig = go.Figure(data=data, layout=layout) return fig
def initPlot(stream_id1, stream_id2, graph_title, max_points=8000): print("Plotly Version=" + plotly.__version__) print("Setting plotly credentials...") tls.set_credentials_file(username=PLOTLY_USERNAME, api_key=PLOTLY_API_KEY) #stream_ids = tls.get_credentials_file()['stream_ids'] ## 1. SETUP STREAM_ID OBJECT # Make instance of stream id object stream_1 = go.Stream( token=stream_id1, # link stream id to 'token' key #maxpoints=max_points # keep a max of 80 pts on screen ) stream_2 = go.Stream( token=stream_id2, # link stream id to 'token' key #maxpoints=max_points # keep a max of 80 pts on screen ) # Initialize trace of streaming plot_init by embedding the unique stream_id trace1 = go.Scatter( x=[], y=[], name='高溫', mode='lines+markers+text', line=dict(shape='spline', color='rgb(255, 128, 0)'), stream=stream_1 # (!) embed stream id, 1 per trace ) trace2 = go.Scatter( x=[], y=[], name='低溫', mode='lines+markers+text', line=dict(shape='spline', color='rgb(102, 178, 255)'), stream=stream_2 # (!) embed stream id, 1 per trace ) data = go.Data([trace1, trace2]) # Add title to layout object layout = go.Layout(title=graph_title, xaxis=dict(title='日期 (年/月/日)', showgrid=False, showline=True, linewidth=2, tickwidth=2), yaxis=dict( title='溫度 (°C)', showgrid=True, showline=False, )) # Make a figure object fig = go.Figure(data=data, layout=layout) # Send fig to Plotly, initialize streaming plot_init, open new tab py.plot(fig, filename=graph_title)
def draw_scatter(df, sd=False, weekend=None): """ Draws scatterplots based on the args df -> Pandas DataFrame sd -> bool (optional) weekend -> bool (optional) """ if weekend is None: dat = df elif weekend: dat = df[df['weekend'] == True] else: dat = df[df['weekend'] == False] if not sd: dat['free_stands_sd'] = dat['free_stands'] dat['avail_bikes_sd'] = dat['avail_bikes'] # available bikes trace1 = go.Scatter( x=dat['time'], y=dat['avail_bikes'], error_y=dict(type='data', array=dat['free_stands_sd'], visible=sd), mode='lines', name='Available Bikes', ) # free stands trace2 = go.Scatter( x=dat['time'], y=dat['free_stands'], error_y=dict(type='data', array=dat['free_stands_sd'], visible=sd), mode='lines', name='Free Stands', ) data = go.Data([trace1, trace2]) layout = go.Layout(xaxis={'title': 'Time'}, yaxis={'title': 'Number'}, legend=dict(x=0, y=1, traceorder='normal', font=dict(family='sans-serif', size=12, color='#000'), bgcolor='#E2E2E2', bordercolor='#FFFFFF', borderwidth=2)) figure = go.Figure(data=data, layout=layout) div = opy.plot(figure, auto_open=False, output_type='div', link_text='Export') return div
def get_plot(x_val, y_val, name): trace1 = go.Scatter(x=x_val, y=y_val) data = go.Data([trace1]) layout = go.Layout(title="Week data of " + name, xaxis={'title': 'Date'}, yaxis={'title': 'Closing Value'}) figure = go.Figure(data=data, layout=layout) div = opy.plot(figure, auto_open=False, output_type='div') return div
def get_data_map(lati, longi, sizem, textm, resp, nivel, mapname, clr_rta): if clr_rta == 'sval': colorlist = ['rgba(255,0,0,0.7)', 'rgba(0,0,255,0.7)'] else: colorlist = [ 'rgba(0, 0, 255,0.7)', 'rgba(0, 255, 0,0.7)', 'rgba(255, 255, 0,0.7)', 'rgba(255, 0, 0,0.7)', 'rgba(153, 0, 153,0.7)', 'rgba(0, 51, 0,0.7)' ] #print(textm) latl = [] longl = [] sizel = [] textl = [] lati = np.asarray(lati) longi = np.asarray(longi) sizem = np.asarray(sizem) for j in np.unique(nivel): pos = np.where(nivel == j)[0] latl.append(lati[pos]) longl.append(longi[pos]) sizel.append(sizem[pos]) textl.append([textm[k] for k in pos]) datamap = go.Data([ go.Scattermapbox( lat=latl[j], lon=longl[j], mode='markers', name=resp[j], marker=go.Marker( size=sizel[j], color=colorlist[j], ), text=textl[j], ) for j in range(len(np.unique(nivel))) ]) layoutmap = go.Layout( title=mapname, hovermode='closest', # sizing= "stretch", # autosize=True, # width = 1200, height=800, mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict(lat=4.6, lon=-74.09), domain=dict(x=[0, 1], y=[0, 1]), pitch=0, style='light', zoom=4.5), ) return datamap, layoutmap
def grafico(consulta, variable, estacion): valor = [] maximo = [] minimo = [] frecuencia = [] for fila in consulta: valor.append(fila.med_valor) maximo.append(fila.med_maximo) minimo.append(fila.med_minimo) frecuencia.append(fila.med_fecha) if variable.var_id == 1: trace = go.Bar(x=frecuencia, y=valor, name='Precipitacion (mm)') data = go.Data([trace]) elif variable.var_id in [6, 8, 9, 10, 11]: trace0 = go.Scatter(x=frecuencia, y=maximo, name='Max', mode='lines', line=dict(color=('rgb(205, 12, 24)'), )) trace1 = go.Scatter(x=frecuencia, y=minimo, name='Min', mode='lines', line=dict(color=('rgb(50, 205, 50)'), )) trace2 = go.Scatter(x=frecuencia, y=valor, name='Media', mode='lines', line=dict(color=('rgb(22, 96, 167)'), )) data = go.Data([trace0, trace1, trace2]) else: trace = go.Scatter(x=frecuencia, y=valor, name='Valor', mode='lines', line=dict(color=('rgb(205, 12, 24)'), )) data = go.Data([trace]) layout = go.Layout( title=estacion.est_codigo + " " + estacion.est_nombre, yaxis=dict(title=variable.var_nombre), ) figure = go.Figure(data=data, layout=layout) div = opy.plot(figure, auto_open=False, output_type='div') return div
def draw_tree(self, genes): gene_nodes = list(map(lambda x: x.split(","), genes)) all_pos = [] all_edges_x = [] all_edges_y = [] all_verts_x = [] all_verts_y = [] names = [] max_y = 0 gene_num = 0 shift = 8.0 for gene in gene_nodes: num_verts = self.count_verts(gene) names += gene[:num_verts] tree = Graph.Adjacency(self.get_adj(gene[:num_verts]), mode=ADJ_UNDIRECTED) lay = tree.layout_reingold_tilford(root=[0], rootlevel=[0]) pos = [lay[k] for k in range(num_verts)] for i in range(len(pos)): pos[i][0] += shift * gene_num all_pos += pos max_height = max([lay[k][1] for k in range(num_verts)]) max_y = max(max_y, max_height) edge_set = [e.tuple for e in tree.es] vert_x_pos = [pos[k][0] for k in range(num_verts)] vert_y_pos = [pos[k][1] for k in range(num_verts)] edge_x_pos = [] edge_y_pos = [] for edge in edge_set: edge_x_pos += [pos[edge[0]][0], pos[edge[1]][0], None] edge_y_pos += [pos[edge[0]][1], pos[edge[1]][1], None] all_edges_x += edge_x_pos all_edges_y += edge_y_pos all_verts_x += vert_x_pos all_verts_y += vert_y_pos gene_num += 1 for i in range(len(all_verts_y)): all_verts_y[i] = 2 * max_y - all_verts_y[i] for i in range(len(all_edges_y)): if all_edges_y[i] is not None: all_edges_y[i] = 2 * max_y - all_edges_y[i] lines, dots = self.draw_objects(all_edges_x, all_edges_y, all_verts_x, all_verts_y, names) data = go.Data([lines, dots]) fig = dict(data=data, layout=self.get_layout(max_y, all_pos, names)) fig['layout'].update( annotations=self.make_annotations(max_y, all_pos, names)) offline.plot(fig, filename="Gene_Expression_Trees.html")
def Temp_Humid(request, pk): sensor = Sensor.objects.get(pk=pk) #project_id = sensor.project.id #sensor_id = sensor.id age = [] temp = [] hum = [] temphum_data = Temp_Hum_Data.objects.filter(sensor=sensor) age_list = [] for items in temphum_data: d_age = items.approx_age """ages = items.approx_age age_list.append(ages) d_age = round((age_list[-1] - age_list[0]), 2)""" age.append(d_age) d_temp = items.approx_temp temp.append(d_temp) d_hum = items.approx_hum hum.append(d_hum) #plot_hum = go.Scatter(dict(x=age, y=hum, name='humidity', marker={'color': 'blue', 'symbol': 104, 'size': 10}, mode="lines")) plot_temp = go.Scatter( dict(x=age, y=temp, name='temperature', marker={ 'color': 'red', 'symbol': 104, 'size': 10 }, mode="lines")) #data = go.Data([plot_hum, plot_temp]) data = go.Data([plot_temp]) #layout=go.Layout(title="Concrete Temperature & Humidity Graph", xaxis={'title':'Age (hr)'}, yaxis={'title':'Temperature (C)'}) layout = go.Layout(title="Concrete Temperature Graph", xaxis={'title': 'Age (hr)'}, yaxis={'title': 'Temperature (C)'}) figure = go.Figure(data=data, layout=layout) temp_graph = ply.plot(figure, auto_open=False, output_type='div') #last_data = temphum_data.last() #current_temp = round(float(last_data.approx_temp), 2) #current_hum = round(float(last_data.approx_hum), 2) context = { 'temp_graph': temp_graph, #'current_temp': current_temp, #'current_hum': current_hum, 'sensor': sensor, } return render(request, 'sensors/Temp_Humid.html', context)
def plotDataHist(hdf5, filetype, outfolder, viewplot, binsize): # open hdf5 file f = h5py.File(hdf5, "r") # extract data from file for ID, dset in f.items(): chrom = dset.attrs["chrom"].decode("utf-8") # chromosome chromStart = dset.attrs["chromStart"] # start coordinate chromEnd = dset.attrs["chromEnd"] # end coordinate x_data = np.arange(chromStart, chromEnd) # position np.array (end exclusive) bamIDs = list(dset.dtype.names) # list of bamIDs subplots = list(range(1, len(dset.dtype) + 1)) # list of subplot numbers # create subplot fig = tls.make_subplots(rows=len(subplots), subplot_titles=bamIDs, vertical_spacing=0.05) # Update 'data' key in fig with a Histogram object for every BAM to respective subplot fig['data'] = go.Data([ make_trace_hist(x_data, dset[BAM], BAM, binsize, index) for index, BAM in enumerate(bamIDs, start=1) ]) # specify layout fig = setLayout(fig, chrom, chromStart, chromEnd, subplots, ID) fig = addSlider(fig) # files saved to specified output folder and named by ROI if filetype == None: plot_url = plotly.offline.plot(fig, filename=str(outfolder) + "/" + str(chrom) + "_.hist", auto_open=viewplot) elif (filetype == 'svg') or (filetype == 'webp'): # saves file types [png, jpeg, svg, webp] AND HTML, but must open plot in web browser plot_url = plotly.offline.plot( fig, filename=str(outfolder) + "/" + str(chrom) + "_.hist", image=filetype, image_filename=str(chrom) + "_.hist", auto_open=viewplot) else: # automatically saves files of type [png, jpeg] without opening browser # No HTML file saved py.image.save_as(fig, filename=str(outfolder) + "/" + str(chrom) + "_.hist" + filetype) f.close() printer.write("Figure completed.")
def update_plot(year_value, xaxis_value, yaxis_value, yaxis_type): """ Top Right graph callback """ dff = df[(df["year"] >= year_value[0]) & (df["year"] <= year_value[1])] dff = dff.groupby([xaxis_value, yaxis_value]).count()['ID'] data = go.Data([ go.Scatter( x=[i[0] for i in dff.index], y=[i[1] for i in dff.index], text=list(dff), mode='markers', marker={ 'symbol': 'circle', 'size': list(dff) / np.max(list(dff)) * 100, 'color': '#0C8522' }, hoverlabel={ 'bgcolor': '#D2D2D2', 'font': { 'color': 'black' }, }, ) ], style={'color': '#D2D2D2'}) layout = go.Layout( autosize=True, xaxis={ 'gridcolor': '#696969', 'gridwidth': 1, 'color': '#D2D2D2', 'autorange': True, 'title': xaxis_value, 'showspikes': True }, yaxis={ 'gridcolor': '#696969', 'gridwidth': 1, 'color': '#D2D2D2', 'autorange': True, 'title': yaxis_value, }, margin={ 'l': 40, 'b': 40, 't': 10, 'r': 0 }, hovermode='closest', paper_bgcolor='#464646', plot_bgcolor='#464646', ) return go.Figure(data=data, layout=layout)
def simple_indicator(request, indicator_id): request.breadcrumbs([ ('Indicator List', reverse('list_indicator_page')), ]) context, reports_df = _retrieve_data_frame(request, indicator_id) indicator = context['indicator'] # hence set the location where the report is based. i.e the child current # selected location. context['report'] = mark_safe( reports_df.to_html(na_rep='-', classes='table table-striped\ table-bordered dataTable table-hover table-sort')) variable_names = indicator.active_variables() report_locations = context['report_locations'] def make_hover_text(row): return '<br />'.join([ '%s: %d' % (name, row[name]) for name in variable_names if str(row[name]).isdigit() ]) reports_df['hover-text'] = reports_df.apply(make_hover_text, axis=1) if report_locations: trace1 = go.Bar( x=reports_df.index, y=reports_df[indicator.REPORT_FIELD_NAME], x0=0, y0=0, name=indicator.name, text=reports_df['hover-text'], ) data = go.Data([trace1]) margin = go.Margin(pad=15) layout = go.Layout( title=indicator.name, xaxis={'title': report_locations[0].type.name}, yaxis={'title': 'Values per %s' % report_locations[0].type.name}, margin=margin, annotations=[ dict( x=xi, y=yi, text=str(yi), xanchor='center', yanchor='bottom', showarrow=False, ) for xi, yi in zip(reports_df.index, reports_df[ indicator.REPORT_FIELD_NAME]) ]) figure = go.Figure(data=data, layout=layout) graph_div = opy.plot(figure, auto_open=False, output_type='div', show_link=False) context['graph'] = mark_safe(graph_div) return render(request, 'indicator/simple_indicator.html', context)
def plot_heat_map(plot_x, plot_y, plot_z): """ Helper to plot heat map """ trace = { "x": plot_x, "y": plot_y, "z": plot_z, "colorscale": [[0.0, "rgb(158,1,66)"], [0.1, "rgb(213,62,79)"], [0.2, "rgb(244,109,67)"], [0.3, "rgb(253,174,97)"], [0.4, "rgb(254,224,139)"], [0.5, "rgb(255,255,191)"], [0.6, "rgb(230,245,152)"], [0.7, "rgb(171,221,164)"], [0.8, "rgb(102,194,165)"], [0.9, "rgb(50,136,189)"], [1.0, "rgb(94,79,162)"]], "type": "heatmap" } data = go.Data([trace]) layout = { "legend": { "bgcolor": "#F5F6F9", "font": { "color": "#4D5663" } }, "paper_bgcolor": "#F5F6F9", "plot_bgcolor": "#F5F6F9", "xaxis1": { "gridcolor": "#E1E5ED", "tickfont": { "color": "#4D5663" }, "title": "", "titlefont": { "color": "#4D5663" }, "zerolinecolor": "#E1E5ED" }, "yaxis1": { "gridcolor": "#E1E5ED", "tickfont": { "color": "#4D5663" }, "title": "", "titlefont": { "color": "#4D5663" }, "zeroline": False, "zerolinecolor": "#E1E5ED" } } fig = go.Figure(data=data, layout=layout) return fig
def plot_chart(sprint_info, total_story_points, actual_remaining): team_name = "YaST" if team == "y" else "User space" date_list = get_sprint_date_interval(sprint_info) text_list = [] for date in actual_remaining.keys(): story_list = actual_remaining[date]['story_list'] text_list.append('<br>'.join(story_list)) if len( story_list) else text_list.append(None) trace_ideal_burn = go.Scatter( x=date_list, y=[ x / 9.0 for x in range(9 * total_story_points, -1, -total_story_points) ], name="Ideal stories remaining", textsrc="gohals:114:c99b6e", type="scatter", uid="2b2777", xsrc="gohals:114:5be4af", ysrc="gohals:114:c99b6e", hoverlabel=dict(font=dict(size=20))) trace_current_burn = go.Scatter( x=date_list, y=list(actual_remaining[date]['value'] for date in actual_remaining.keys()), hovertext=text_list, name="Actual stories remaining", textsrc="gohals:114:c99b6e", type="scatter", uid="a7c235", xsrc="gohals:114:5be4af", ysrc="gohals:114:d49a4c", hoverlabel=dict(font=dict(size=20, color="white"))) data = go.Data([trace_ideal_burn, trace_current_burn]) layout = go.Layout(autosize=True, title="Sprint " + str(sprint_info['num']) + " - Burndown chart - " + team_name + " QSF team", xaxis=dict( title="Iteration Timeline (working days)", autorange=True, range=date_list, type="category", tickvals=date_list, ), yaxis=dict( title="Sum of Story Estimates (story points)", autorange=True, type="linear"), font=dict(family='Courier New, monospace', size=18, color='#7f7f7f')) fig = go.Figure(data=data, layout=layout) plot(fig)
def plotly_prob(mu, log_goal): plotly.tools.set_credentials_file\ (username='******', api_key='3FTZrZRMQSDYshs8rxJ7') variance = 0.71 x = np.linspace(mu - 5 * variance, mu + 5 * variance, 100) x_new = [10**w for w in x] y = mlab.normpdf(x, mu, (variance**(1 / 2))) x1 = np.linspace(log_goal, mu + 5 * variance, 100) x1_new = [10**w for w in x1] y1 = mlab.normpdf(x1, mu, (variance**(1 / 2))) x2 = [10**log_goal for _ in range(100)] y2 = np.linspace(0, mlab.normpdf(log_goal, mu, variance**(1 / 2)), 100) py.sign_in(username='******', api_key='3FTZrZRMQSDYshs8rxJ7') trace1 = { "x": x_new, "y": y, "name": "PDF of Prediction Number", "type": "scatter" } trace2 = { "x": x1_new, "y": y1, "fill": "tozeroy", "name": "Prob(Prediction > Your Goal)", "type": "scatter" } trace3 = {"x": x2, "y": y2, "name": "Your Goal", "type": "scatter"} layout = go.Layout( title='Your Chance to Reach the Goal', font=dict(family='Courier New, monospace', size=24, color='#7f7f7f'), xaxis=dict(title='Supporter Number', type='log', autorange=True, titlefont=dict(family='Courier New, monospace', size=24, color='#7f7f7f')), yaxis=dict(title='Probability', titlefont=dict(family='Courier New, monospace', size=24, color='#7f7f7f'))) data = go.Data([trace1, trace2, trace3]) fig = go.Figure(data=data, layout=layout) div = plotly.offline.plot(fig, show_link=False, output_type="div", include_plotlyjs=False) #py.iplot(fig) return div
def interactive_3d_plot(data, names): scatt = go.Scatter3d(x=data[:, 0], y=data[:, 1], z=data[:, 2], mode='markers', text=names) data = go.Data([scatt]) layout = go.Layout(title="Anomaly detection") figure = go.Figure(data=data, layout=layout) py.iplot(figure)
def barchart_warehouse(x_data, y_data, name): x = x_data y = y_data plot1 = gro.Bar(x=x, y=y, name=name, marker=dict(color='rgba(255,0,0,0.8)')) input = gro.Data([plot1]) design = gro.Layout(xaxis=dict(tickangle=-45), width=550, height=450) fig = gro.Figure(data=input, layout=design) div1 = ofpy.plot(fig, auto_open=False, output_type='div', show_link=False) return div1
def getMapData(pointsDic): return go.Data([ go.Scattermapbox( #lat=lats, #lon=longs, mode='markers', #text=texts ) ])
def draw_graph(G, stations): node_trace = go.Scatter( x=[], y=[], text=[], mode='markers+text', textposition='top center', textfont=dict( family='arial', size=3, color='rgb(0,0,0)' ), hoverinfo='none', marker=go.Marker( showscale=False, color='rgb(200,0,0)', opacity=0.3, size=8, line=go.Line(width=1, color='rgb(0,0,0)'))) node_positions = {} for id in stations.index: lat, lng = stations.loc[id, ["Latitude", "Longitude"]].values node_positions[id] = [lat, lng] node_trace['x'].append(lat) node_trace['y'].append(lng) # node_trace['text'].append(id) # The edges will be drawn as lines: edge_trace = go.Scatter( x=[], y=[], line=go.Line(width=2, color='rgb(10,10,10)'), hoverinfo='none', mode='lines') for id in node_positions.keys(): for neigh_info in G.neighbors(id): x0, y0 = node_positions[id] x1, y1 = node_positions[neigh_info[0]] edge_trace['x'].extend([x0, x1, None]) edge_trace['y'].extend([y0, y1, None]) # Create figure: fig = go.Figure(data=go.Data([edge_trace, node_trace]), layout=go.Layout( title='Sample Network', titlefont=dict(size=16), showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), xaxis=go.XAxis(showgrid=False, zeroline=False, showticklabels=False), yaxis=go.YAxis(showgrid=False, zeroline=False, showticklabels=False))) py.plot(fig)
def GraphTHPlotly(df_delta, pts_names): # inizializzazione variabili traces = [] l_visible = [False for i in range(0, len(pts_names))] l_buttons = [] i = 0 # per ogni punto misurato vengono presi i dati da graficare dalla variabile # di tipo DataFrame 'df_delta' for nome_pto in pts_names: # definizione 'traces' da rappresentare in asse x e y traces.append( plotly.graph_objs.Scatter( x=df_delta.loc[nome_pto].time, y=df_delta.loc[nome_pto].H, mode='lines', # nome della serie di dati name=nome_pto)) # definizione del menù a tendina per la selezione della serie da rappresentare # nella posizione i-esima della lista 'l_visible_i' viene scritto True l_visible_i = copy.deepcopy(l_visible) l_visible_i[i] = True l_buttons.append({ "args": ["visible", l_visible_i], "label": nome_pto, "method": "restyle" }) i = i + 1 data = go.Data(traces) # definizione delle caratteristiche dell'asse y yaxis_par = dict(title='delta H [m]', titlefont=dict(family='Arial', size=12, color='black'), showticklabels=True, tickangle=0, tickfont=dict(family='Arial', size=12, color='black'), range=[-0.04, 0.04]) # impostazione del layout del grafico layout = { 'title': 'Grafico delta H STZ004', 'yaxis': yaxis_par, 'updatemenus': [{ 'x': -0.05, 'y': 1, 'yanchor': 'top', 'buttons': l_buttons }] } fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig, filename='graph_TH.html')
def get_context_data(self, **kwargs): x = forecast() context = super(Graph, self).get_context_data(**kwargs) c_name = x['city']['name'] z = [] d = [] for i in range(x['cnt']): tem = x['list'][i]['main']['temp'] date = x['list'][i]['dt_txt'] z.append(tem) d.append(date) print(z, d) trace1 = go.Scatter(x=d, y=z, marker={'color': 'red', 'symbol': 104, 'size': "10"}, mode="lines", name='1st Trace') data = go.Data([trace1]) layout = go.Layout(title=str(c_name + ' temperature'), xaxis={'title': 'date'}, yaxis={'title': 'temperature'}) figure = go.Figure(data=data, layout=layout) div = opy.plot(figure, auto_open=False, output_type='div') context['graph'] = div c_name = x['city']['name'] z = [] d = [] for i in range(x['cnt']): try: tem = x['list'][i]['rain']['3h'] date = x['list'][i]['dt_txt'] z.append(tem) d.append(date) except Exception as e: z.append(0) date = x['list'][i]['dt_txt'] d.append(date) pass print(z, d) trace1 = go.Scatter(x=d, y=z, marker={'color': 'blue', 'symbol': 104, 'size': "10"}, mode="lines", name='1st Trace') data = go.Data([trace1]) layout = go.Layout(title=str(c_name + ' rainfall '), xaxis={'title': 'Time'}, yaxis={'title': 'rainfall (mm)'}) figure = go.Figure(data=data, layout=layout) div2 = opy.plot(figure, auto_open=False, output_type='div') context['graph2'] = div2 return context
def plot_dist(path, values, label): trace = go.Histogram(x=values, xbins=dict(start=min(values), size=0.25, end=max(values)), marker=dict(color='rgb(0, 0, 100)')) layout = go.Layout( title="Histogram Frequency Counts" ) fig = go.Figure(data=go.Data([trace]), layout=layout) py.offline.plot(fig, filename=path)
def _plot_site_monthly_timeseries(self, plotname): """Plot Site monthly aggregate timeseries.""" df = pd.DataFrame() trace1 = Bar(x=df.month, y=self.data, name='') fig = go.Figure(data=go.Data([trace1])) plot_url = py.iplot(fig, filename=plotname, sharing='private') return df, plot_url
def dr_mul_line(df, ftg='tmp/tmp_plotly.html', m_tkAng=-20, m_dtick=5, m_title='多周期分时数据', xlst=['t1', 't5', 't15', 't30', 't60']): xdat = pygo.Data([]) for xsgn in xlst: r_xnam = 'r_' + xsgn r_xnam = pygo.Scatter( x=df.index, y=df[xsgn], name=xsgn, connectgaps=True, ) # xdat.extend([r_xnam]) # lay = pygo.Layout( title=m_title, xaxis=pygo.XAxis( gridcolor='rgb(180, 180, 180)', mirror='all', showgrid=True, showline=True, ticks='outside', #'inside', # dtick=m_dtick, tickangle=m_tkAng, # type='category', categoryarray=df.index, ), ) #lay = pygo.Layout( r_vol = pygo.Bar( x=df.index, #df['xtim'], y=df['volume'], name='volume', yaxis='y2', opacity=0.6, marker=dict( color='rgb(158,202,225)', line=dict( color='rgb(8,48,107)', width=1.5, ), ), ) #r_vol # fig['data'].extend([r_vol]) # #xdat = pygo.Data([r_t1,r_t5,r_t15,r_t30,r_t60]) fig = pygo.Figure(data=xdat, layout=lay) pyplt(fig, filename=ftg, show_link=False)
def plot_graph(test_accuracy): py.sign_in('VikramShenoy', 'x1Un4yD3HDRT838vRkFA') training_accuracy = [] history = np.load("history.npy", allow_pickle=True) training_loss = history.item().get('train_loss') train_accuracy = history.item().get('train_accuracy') epochs = list(range(1, len(training_loss) + 1)) for i in range(0, len(train_accuracy)): training_accuracy.append(train_accuracy[i].item() / 100) testing_accuracy = 98.64 #test_accuracy trace0 = go.Scatter(x=epochs, y=training_accuracy, mode="lines", name="Training Accuracy") trace1 = go.Scatter(x=epochs, y=training_loss, mode="lines", name="Training Loss") data = go.Data([trace0, trace1]) layout = go.Layout() fig = go.Figure(data=data, layout=layout) fig['layout']['xaxis'].update(title="Number of Epochs", range=[min(epochs), max(epochs)], dtick=len(epochs) / 10, showline=True, zeroline=True, mirror='ticks', linecolor='#636363', linewidth=2) fig['layout']['yaxis'].update(title="Training Loss and Accuracy", range=[0, 1.05], dtick=0.1, showline=True, zeroline=True, mirror='ticks', linecolor='#636363', linewidth=2) py.image.save_as(fig, filename="Training_Graph.png") print("Training Graph Created") x_axis = ["Training", "Testing"] y_axis = [training_accuracy[-1] * 100, testing_accuracy] trace2 = go.Bar(x=x_axis, y=y_axis, width=[0.3, 0.3]) data = [trace2] layout = go.Layout() fig = go.Figure(data=data, layout=layout) fig['layout']['xaxis'].update(title="Mode", showline=True) fig['layout']['yaxis'].update(title="Accuracy") py.image.save_as(fig, filename="Accuracy_Graph.png") print("Accuracy Graph Created") return
def update_plot(year_value, xaxis_value, xaxis_type, yaxis_value, yaxis_type): """ Top Right graph callback """ dff = df[df['year'] == year_value] data = go.Data([ go.Scatter( x=dff[xaxis_value], y=dff[yaxis_value], text=dff['legend'], mode='markers', marker={ 'symbol': 'circle', 'size': dff['impact-e'], 'color': '#C2FF0A' }, hoverlabel={ 'bgcolor': '#FFF', 'font': { 'color': 'black' }, }, ) ], style={'color': '#FFF'}) layout = go.Layout( autosize=True, xaxis={ 'color': '#FFF', 'autorange': True, 'title': xaxis_value, 'type': 'Linear' if xaxis_type == 'Linear' else 'log', 'showspikes': True }, yaxis={ 'color': '#FFF', 'autorange': True, 'title': yaxis_value, 'type': 'Linear' if yaxis_type == 'Linear' else 'log' }, margin={ 'l': 40, 'b': 40, 't': 10, 'r': 0 }, hovermode='closest', paper_bgcolor='#191a1a', plot_bgcolor='#191a1a', ) return go.Figure(data=data, layout=layout)
def upload_reference_graph(graph_unique_name=''): trace_list = get_reference_trace_for_append(graph_unique_name) try: #update reference trace fig = graph_objs.Figure(data=graph_objs.Data([trace_list]), layout=get_layout(graph_unique_name)) py.plot(fig, filename=graph_unique_name, fileopt='overwrite', auto_open=False) #clean graph from memory to force graph traces reload in the right order clean_graph_memory(graph_unique_name) L.l.info('New reference graph {} uploaded ok'.format(graph_unique_name)) except PlotlyListEntryError, ex: L.l.warning('Error uploading new reference graph {} err {}'.format(graph_unique_name, ex))
def scatter_line_chart(df, y_title): """Generate a reproducible plotly scatter and line plot.""" if len(df.columns) == 3: x_axis, y_axis, factor = df.columns data = go.Data([ go.Scatter(x=sub[x_axis], y=sub[y_axis], name=key) for key, sub in df.groupby(factor, as_index=False, sort=False) ]) else: x_axis, y_axis = df.columns data = go.Data([go.Scatter(x=df[x_axis], y=df[y_axis])]) layout = go.Layout( width=650, height=500, xaxis=go.XAxis( title="Commit Hash" if x_axis == "commit_hash" else "Timestamp", tickangle=-45 if x_axis == "commit_hash" else 0), yaxis=go.YAxis(title=y_title)) return Markup(py.plot(go.Figure(data=data, layout=layout), **_DEFAULT_ARGS))
def plotSelectionsFromDataframes(dataFrames, timezone='Etc/GMT-3'): lines = [] for i, dataFrame in enumerate(dataFrames): dataFrame['header_timestamp'] = pandas.to_datetime(dataFrame['header_timestamp'], unit='ms').dt.tz_localize(timezone) lines.append( plotlygo.Scatter( y=dataFrame.dimension_value, x=dataFrame.header_timestamp, mode = 'lines+markers', name = "Sensor {0}".format(i) ) ) data = plotlygo.Data(lines) layout = plotlygo.Layout(width=1100, height=650) plotly.iplot( plotlygo.Figure(data=data, layout=layout) )
def run(app): mapboxtoken = 'pk.eyJ1IjoidHRob21haWVyIiwiYSI6ImNqZjduZzkzdjF6d2wyd2xubTI3djN4cGwifQ.3-bkCbF2NAzEyTsqK3okWg' zctaPolygonFile = os.getcwd( ) + "/mysite/Datafiles/Map/nyczipcodetabulationareas.geojson" #get geojson for zcta areas geofile = open(zctaPolygonFile) geojsonlayer = json.load(geofile) geofile.close() centerLat = 40.702793 centerLong = -73.965584 #map mapData = go.Data( [go.Scattermapbox(lat=[centerLat], lon=[centerLong], mode='markers')]) mapLayout = go.Layout(height=800, autosize=True, margin=dict(l=0, r=0, t=0, b=0), hovermode='closest', mapbox=dict(layers=[ dict(sourcetype='geojson', source=geojsonlayer, type='fill', color='rgba(163,22,19,0.8)') ], accesstoken=(mapboxtoken), bearing=0, center=dict(lat=centerLat, lon=centerLong), pitch=0, zoom=9.95, style='light')) #UI application #app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Test App'), html.Div(children=''' Hover to see values, click to see area dashboard: '''), dcc.Graph(id='zcta-example', style={'height': '90vh'}, figure=dict(data=mapData, layout=mapLayout)) ]) return app #run #if __name__ == '__main__': # app.run_server(debug=True)