我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用plotly.graph_objs.Layout()。
def plot_frame(dataframe, uname=None, api_key=None, mode='lines', line={}): try: import plotly.plotly as ply import plotly.tools as ptls from plotly.graph_objs import Scatter, Layout, Data, Figure except ImportError: raise InvalidOperationException("Please install the Python plotly bindings") if uname and api_key: ply.sign_in(uname, api_key) c1 = dataframe.ch1 c2 = dataframe.ch2 x = list(range(len(c1))) t1 = Scatter(x=x, y=c1, mode=mode, line=line) t2 = Scatter(x=x, y=c2, mode=mode, line=line) layout = Layout(title="Moku:Lab Frame Grab") data = Data([t1, t2]) fig = Figure(data=data, layout=layout) return ply.plot(fig)
def layout_2D(type=None, title=None): layout = go.Layout( title=title, xaxis=dict( title='Samples' ), yaxis=dict( title='Amplitude' ) ) if type == 'time': layout.title = 'Time domain plot' layout.xaxis.title = 'Time [s]' elif type == 'linFFT': layout.title = 'Frequency domain plot (linear)' layout.yaxis.title = 'Amplitude [dB]' layout.xaxis.title = 'Frequency [Hz]' elif type == 'logFFT': layout.title = 'Frequency domain plot (logarithmic)' layout.yaxis.title = 'Amplitude [dB]' layout.xaxis.title = 'Frequency [Hz]' layout.xaxis.type = 'log' return layout
def plot_results(results, plot_name='temp-plot.html'): ''' results is a list of dictionaries, each of which defines a trace e.g. [{'x': x_data, 'y': y_data, 'name': 'plot_name'}, {...}, {...}] Each dictionary's key-value pairs will be passed into go.Scatter to generate a trace on the graph ''' traces = [] for input_args in results: traces.append(go.Scatter(**input_args)) layout = go.Layout( title='Trading performance over time', yaxis=dict( title='Value (USD)' ), ) plot(go.Figure(data=traces, layout=layout), filename=plot_name)
def win_probability_matrix(matrix_df): 'returns the win probability matrix plot as a plotly heatmap' trace = go.Heatmap( z=matrix_df.transpose().values.tolist(), x=matrix_df.columns[::-1], y=matrix_df.columns[::-1], colorscale='Viridis' ) data = [trace] layout = go.Layout( title='Win Probability Matrix', xaxis=dict(title='Loser', ticks=''), yaxis=dict(title='Winner', ticks=''), height=750 ) return offl.plot(dict(data=data, layout=layout), output_type='div')
def running_times(): rospack = rospkg.RosPack() data_path = os.path.join(rospack.get_path('vslam_evaluation'), 'out') df = pd.read_csv(os.path.join(data_path, 'runtimes.txt'), header=None, index_col=0) bars = [] for col_idx in df: this_stack = df[col_idx].dropna() bars.append( go.Bar( x=this_stack.index, y=this_stack.values, name='Thread {}'.format(col_idx))) layout = go.Layout( barmode='stack', yaxis={'title': 'Running time [s]'}) fig = go.Figure(data=bars, layout=layout) url = py.plot(fig, filename='vslam_eval_run_times')
def generate_chart(self, _): try: import plotly import plotly.graph_objs as go data = [[0, 0, 0], [0, 0, 0]] ok, viol = self.results.get_ok_viol() x = ["OK (%d)" % ok, "Tampering (%d)" % viol] for ret in self.results: i = 1 if ret.is_tampering() else 0 data[i][0] += ret.is_aligned() data[i][1] += ret.is_disaligned() data[i][2] += ret.is_single() final_data = [go.Bar(x=x, y=[x[0] for x in data], name="Aligned"), go.Bar(x=x, y=[x[1] for x in data], name="Disaligned"), go.Bar(x=x, y=[x[2] for x in data], name="Single")] fig = go.Figure(data=final_data, layout=go.Layout(barmode='group', title='Call stack tampering labels')) plotly.offline.plot(fig, output_type='file', include_plotlyjs=True, auto_open=True) except ImportError: self.log("ERROR", "Plotly module not available")
def plotVAEplotly(self, logdir, prefix, ctable=None, reverseUtt=False, batch_size=128, debug=False): ticks = [[-1,-0.5,0,0.5,1]]*self.latentDim samplePoints = np.array(np.meshgrid(*ticks)).T.reshape(-1,3) input_placeholder = np.ones(tuple([len(samplePoints)] + list(self.phon.output_shape[1:-1]) + [1])) preds = self.decode_word([samplePoints, input_placeholder], batch_size=batch_size) if reverseUtt: preds = getYae(preds, reverseUtt) reconstructed = reconstructXae(np.expand_dims(preds.argmax(-1), -1), ctable, maxLen=5) data = [go.Scatter3d( x = samplePoints[:,0], y = samplePoints[:,1], z = samplePoints[:,2], text = reconstructed, mode='text' )] layout = go.Layout() fig = go.Figure(data=data, layout=layout) plotly.offline.plot(fig, filename=logdir + '/' + prefix + '_VAEplot.html', auto_open=False)
def scatter_plot(xs, ys=None, xlabel='', ylabel='', title='', lines=False, marker=dict()): layout = Layout( title=title, xaxis=dict(title=xlabel), yaxis=dict(title=ylabel) ) if ys is None: ys = xs xs = list(range(len(xs))) data = [ Scatter(x=xs, y=ys, mode='lines' if lines else 'markers', marker=marker) ] figure = Figure(data=data, layout=layout) plotly.offline.plot(figure, filename=title + '.html')
def get_example_plot_html(number_of_points=30): import plotly.offline from plotly.graph_objs import Scatter, Layout, Bar, Margin data_x = [] data_y = [] for i in range(0, number_of_points): data_x.append(i) data_y.append(random.randint(-10, 10)) return plotly.offline.plot( figure_or_data={ "data": [Scatter(x=data_x, y=data_y)], "layout": Layout(title="Plot Title") }, show_link=False, output_type='div', include_plotlyjs=False, auto_open=False, )
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 plot3D(vizMTX, style='shape', layout=None, normalize=True, logScale=False): """Visualize matrix data, such as from makeMTX(Pnm, dn) Parameters ---------- vizMTX : array_like Matrix holding spherical data for visualization style : string{'shape', 'sphere', 'flat'}, optional Style of visualization. [Default: 'shape'] normalize : Bool, optional Toggle normalization of data to [-1 ... 1] [Default: True] TODO ---- Colorization, contour plot """ if style == 'flat': layout = go.Layout( scene=dict( xaxis=dict(range=[0, 360]), yaxis=dict(range=[0, 181]), aspectmode='manual', aspectratio=dict(x=3.6, y=1.81, z=1) ) ) showTrace(genVisual(vizMTX, style=style, normalize=normalize, logScale=logScale), layout=layout)
def build(self, x, y, title=""): div = plotly.offline.plot({ "data": [Scatter(x=x, y=y)], "layout": Layout(title=title, # xaxis=dict(range=[4200, 5300]), # yaxis=dict(range=[0.5, 2]), ) }, output_type='div', include_plotlyjs=False) return div
def callbacks(self, app): @app.callback( Output(self.ID, 'figure'), [Input(self.SUBSET_ID, 'value'), # Input(SmushedPlot.SELECTED_GENE_ID, 'value'), # Input(SmushedPlot.SELECTED_METADATA_ID, 'value') ]) def update_reads_vs_genes(group_name, selected_gene=None, selected_metadata=None): """When a group is selected, update the reads v genes scatter""" group_barcodes = self._get_dropdown_barcodes(group_name) group_metadata_subset = self.cell_metadata.loc[group_barcodes] x = group_metadata_subset[self.n_molecules_col] y = group_metadata_subset[self.n_genes_col] return { "data": [go.Scatter(x=x, y=y, mode='markers', hoverinfo='text', text=group_metadata_subset.index, customdata=group_metadata_subset.index)], "layout": go.Layout(xaxis={'title': 'Reads per cell'}, yaxis={'title': "Genes per cell"}, margin={'b': 40, 't': 10, 'r': 0}, hovermode='closest', dragmode='select'), }
def plot_labelprop(coords, communities, filename=None, title=''): scatters = [] n_communities = len(np.unique(communities)) scatter = go.Scatter(x=coords[0], y=coords[1], mode='markers', name=communities, hoverinfo='text', text=communities, marker=dict(color=communities, cmin=0.0, cmax=n_communities - 1, colorscale='Viridis' )) fig = { 'data': [scatter], "layout": go.Layout(title=f'Graph layout of cell type clusters: {title}', xaxis={'showticklabels': False}, yaxis={'showticklabels': False}, hovermode='closest', dragmode='select', show_legend=True) } if filename is None: plotly.offline.iplot(fig) else: plotly.offline.plot(fig, filename=filename, image='png')
def label_usage(self): """Returns a pie chart showing usage information for labels. """ c = self.conn.cursor() c.execute('''SELECT gmail_labels FROM messages WHERE gmail_labels != '' AND gmail_labels NOT LIKE '%Chat%';''') counts = {} for row in c.fetchall(): for label in row[0].split(','): if label not in counts: counts[label] = 0 counts[label] += 1 trace = pgo.Pie( labels=counts.keys(), values=counts.values(), marker=dict( colors=[ self.config.get('color', 'primary'), self.config.get('color', 'secondary'), ] ) ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Label Usage' del layout_args['xaxis'] del layout_args['yaxis'] layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[trace], layout=layout))
def thread_sizes(self): """Returns a graph showing thread size information. A "thread" must consist of more than one email. """ c = self.conn.cursor() c.execute('''SELECT COUNT(message_key) AS message_count FROM messages WHERE gmail_labels NOT LIKE '%Chat%' GROUP BY gmail_thread_id HAVING message_count > 1;''') counts = {} for row in c.fetchall(): if row[0] not in counts: counts[row[0]] = 0 counts[row[0]] += 1 data = dict( x=counts.keys(), y=counts.values(), name='Emails in thread', mode='lines+markers', marker=dict( color=self.config.get('color', 'primary'), ), ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Thread Sizes' layout_args['xaxis']['title'] = 'Number of messages' layout_args['yaxis']['title'] = 'Number of threads' layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[pgo.Scatter(**data)], layout=layout))
def talk_times(self): """Returns a plotly graph showing chat habits by hour of the day (UTC). """ c = self.conn.cursor() c.execute('''SELECT strftime('%H', `date`) AS hour, COUNT(message_key) AS talk_messages FROM messages WHERE gmail_labels LIKE '%Chat%' GROUP BY hour ORDER BY hour ASC;''') data = OrderedDict() for row in c.fetchall(): data[row[0]] = row[1] total_messages = sum(data.values()) percentages = OrderedDict() for hour in data.keys(): percentages[hour] = str(round(float(data[hour])/float(total_messages) * 100, 2)) + '%' data_args = dict( x=data.keys(), y=data.values(), text=percentages.values(), name='Chat messages', marker=dict( color=self.config.get('color', 'primary') ), fill='tozeroy', ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Chat Times (UTC)' layout_args['xaxis']['title'] = 'Hour of day (UTC)' layout_args['yaxis']['title'] = 'Chat messages' trace = pgo.Scatter(**data_args) layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[trace], layout=layout))
def plotly_samtools_depth(ids_depths): n_positions = len(ids_depths[max(ids_depths, key=lambda x: len(set(ids_depths[x])))]) traces = [] for id, depths in sorted(ids_depths.items()): traces.append( go.Scattergl( x=list(range(1, n_positions)), y=depths, mode='lines', name=id, text=id)) layout = go.Layout( title='Depth of coverage', xaxis=dict( title='Position', gridcolor='rgb(255, 255, 255)', gridwidth=2), yaxis=dict( title='Depth', gridcolor='rgb(255, 255, 255)', gridwidth=2, type='log'), paper_bgcolor='rgb(243, 243, 243)', plot_bgcolor='rgb(243, 243, 243)') fig = go.Figure(data=traces, layout=layout) py.plot(fig, filename='depths.html')
def plotly_variants(ids_data): import plotly.offline as py import plotly.graph_objs as go traces = [] for id, data in sorted(ids_data.items()): traces.append( go.Scattergl( x=data['pos'], y=data['max_alt'], mode='markers', name=id, text=id)) layout = go.Layout( title='Variants', xaxis=dict( title='Position', gridcolor='rgb(255, 255, 255)', gridwidth=2), yaxis=dict( title='Abundance', gridcolor='rgb(255, 255, 255)', gridwidth=2, type='linear'), paper_bgcolor='rgb(243, 243, 243)', plot_bgcolor='rgb(243, 243, 243)') fig = go.Figure(data=traces, layout=layout) py.plot(fig, filename='variants.html')
def callback(*args): """dummy function""" # pylint: disable=unused-argument chart = { "data": [ Scatter(x=[1, 2, 3, 4], y=[4, 1, 3, 7]) ], "app": PlotLayout( title="hello world" ) } viz.do_all(chart) # pylint: disable=unused-argument
def createGraph(num_points, colname): sensor_data = GenScatterData(colname, num_points) plotly.offline.plot({ 'data': [ GenScatter(sensor_data), ], 'layout': Layout(title='Data for %s' % colname) })
def open_figure(self, fig, props): """Creates a new figure by beginning to fill out layout dict. The 'autosize' key is set to false so that the figure will mirror sizes set by mpl. The 'hovermode' key controls what shows up when you mouse around a figure in plotly, it's set to show the 'closest' point. Positional agurments: fig -- a matplotlib.figure.Figure object. props.keys(): [ 'figwidth', 'figheight', 'dpi' ] """ self.msg += "Opening figure\n" self.mpl_fig = fig self.plotly_fig['layout'] = go.Layout( width=int(props['figwidth'] * props['dpi']), height=int(props['figheight'] * props['dpi']), autosize=False, hovermode='closest') self.mpl_x_bounds, self.mpl_y_bounds = mpltools.get_axes_bounds(fig) margin = go.Margin( l=int(self.mpl_x_bounds[0] * self.plotly_fig['layout']['width']), r=int( (1-self.mpl_x_bounds[1]) * self.plotly_fig['layout']['width']), t=int((1-self.mpl_y_bounds[1]) * self.plotly_fig['layout'][ 'height']), b=int(self.mpl_y_bounds[0] * self.plotly_fig['layout']['height']), pad=0) self.plotly_fig['layout']['margin'] = margin
def show(self, vis_mode = '3D', title = '') : self.M.layout['showlegend'] = True (wid, div_id) = self.M.iplot(title) (costs_curve, div_costs_curve, cost_values) = self.costs_curve() pause(1) hb = self.show_training(div_id, div_costs_curve, cost_values) self.training_widget = VBox([hb, wid, costs_curve], layout = Layout(width='100%', justify_content='center')) display(self.training_widget) return div_id
def costs_curve(self) : values = self.cost_values s = unique(values) values = values - s[0] + .5 * (s[1] - s[0]) # Create a trace trace = go.Scatter( x = arange(len(values))+1, y = array(values), name = 'Cost excess' ) mark = go.Scatter( x = array([1]), y = array([values[0]]), marker = dict( color = "rgb(0, 0, 128)", size = 15 ), name = 'Current value', mode = 'markers' ) data = [trace, mark] layout = go.Layout( title='Cost excess across iterations', width=800, height=800, legend = dict( x = .8, y = 1), #xaxis = dict(range = [-3,3]), #yaxis = dict(range = [-3,3]) yaxis=dict( type='log', autorange=True ) ) return my_iplot(go.Figure(data=data, layout=layout)) + (values,)
def interactive_show(self, mode='', ax = None) : "Manifold display." self.layout = go.Layout( title='', width=800, height=800, legend = dict( x = .8, y = 1), xaxis = dict(range = [-2,2]), yaxis = dict(range = [-2,2]) )
def setup_layout(self) : "Setup the axis properties." axis = dict( showbackground=True, backgroundcolor='rgb(230, 230, 230)', gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)' ) xaxis = axis.copy() xaxis['range'] = [-1.1,1.1] yaxis = axis.copy() yaxis['range'] = [-1.1,1.1] zaxis = axis.copy() zaxis['range'] = [-1.1,1.1] aspectratio=dict(x=1, y=1, z=1) self.layout = go.Layout( title='Kendall Triangles', width='100%', height= 800, scene=go.Scene( xaxis=go.XAxis(xaxis), yaxis=go.YAxis(yaxis), zaxis=go.ZAxis(zaxis), aspectratio=dict( x=aspectratio['x'], y=aspectratio['y'], z=aspectratio['z']), ) )
def show(self, mode='', ax = None) : "Manifold display." self.layout = go.Layout( title='', width=800, height=800, legend = dict( x = .8, y = 1), xaxis = dict(range = [-3,3]), yaxis = dict(range = [-3,3]) )
def generate_group_bar_charts(y_values, x_values, trace_header, output_directory, output_file_name): """ Plots multiple bar graphs on same graph example usage: generate_group_bar_charts([ [5.10114882, 5.0194652482, 4.9908093076], [4.5824497358, 4.7083614037, 4.3812775722], [2.6839471308, 3.0441476209, 3.6403820447] ], ['#kubuntu-devel', '#ubuntu-devel', '#kubuntu'], ['head1', 'head2', 'head3'], '/home/rohan/Desktop/', 'multi_box' ) Args: x_in (list of int): x_axis data y_in (list of int): y_axis data output_drectory(str): location to save graph output_file_name(str): name of the image file to be saved Returns: null """ data = [ go.Bar( x=x_values, y=y_values[i], name=trace_header[i] ) for i in range(len(y_values)) ] layout = go.Layout( barmode='group' ) fig = go.Figure(data=data, layout=layout) py.image.save_as(fig, output_directory + "/" + output_file_name+".png")
def csv_heatmap_generator_plotly(in_directory, output_directory, output_file_name): """ Plots heatmaps for all the csv files in the given directory Args: in_directory (str): location of input csv files output_drectory(str): location to save graph output_file_name(str): name of the image file to be saved Returns: null """ file_list = glob.glob(in_directory+"*.csv") for file in file_list: csv_data = genfromtxt(file, delimiter=',') trace = go.Heatmap( z=csv_data, x=list(range(48)), y=list(range(1, 12)), colorscale=[ [0, 'rgb(255, 255, 204)'], [0.13, 'rgb(255, 237, 160)'], [0.25, 'rgb(254, 217, 118)'], [0.38, 'rgb(254, 178, 76)'], [0.5, 'rgb(253, 141, 60)'], [0.63, 'rgb(252, 78, 42)'], [0.75, 'rgb(227, 26, 28)'], [0.88, 'rgb(189, 0, 38)'], [1.0, 'rgb(128, 0, 38)'] ] ) data = [trace] layout = go.Layout(title='HeatMap', width=800, height=640) fig = go.Figure(data=data, layout=layout) py.image.save_as(fig, filename=in_directory+file[file.rfind("/")+1:-4]+'_heatmap.png')
def update_graph(threshold): # ''' # Description: Updates the threshold graph with only the words that are between the two user selected thersholds from the dash slider. # Params: Threshold tuple (lower threshold, upper threshold) # Returns: Graph data for only the words and word frequencies of the words between the two thresholds. # ''' global interface_obj ## Get bottom & top thresholds and rebuild the word/doc. freq. dataframe bottom_threshold = float(threshold[0]) * float(5) / float(100) * float(len(interface_obj.clean_df)) top_threshold = float(threshold[1]) * float(5) / float(100) * float(len(interface_obj.clean_df)) new_df1 = interface_obj.freq_matrix.where(interface_obj.freq_matrix[1] >= bottom_threshold).dropna() new_df2 = interface_obj.freq_matrix.where(interface_obj.freq_matrix[1] <= top_threshold).dropna() ## Merge on words above bottom thresh. and words below top thresh. interface_obj.freq_matrix_keep = pd.merge(new_df1, new_df2, how='inner', on=[0]) return { ## Set x as doc. freq. of words within bottom and top thresholds 'data' : [graph.Scattergl( x = interface_obj.freq_matrix_keep['1_y'], y = interface_obj.freq_matrix_keep.index, mode = 'markers', text = interface_obj.freq_matrix_keep[0] )], ## Rebuild range of x and y axis with min and max of new dataframe 'layout' : graph.Layout( xaxis = {'title' : 'Document Frequency'}, yaxis = {'title' : 'Word Ids (ordered by doc. freq.)'}, hovermode = 'closest', ) }
def skew_plot(skew_list): data = [go.Bar( x=['True', 'False'], y=[skew_list[1], skew_list[2]], )] layout = go.Layout(title="Skew Balance", width=300, height=300) fig = go.Figure(data=data, layout=layout) iplot(fig, config={'showLink' : False, 'displaylogo' : False, 'modeBarButtonsToRemove' : ['sendDataToCloud']})
def plotly_metric_plot(alg_names, x_axis, y_axis, color_list=None, title=None): #TODO: Check if the x axis and y axis are the same length if color_list == None: color_list = ['rgb(244, 167, 66)', 'rgb(49,130,189)', 'rgb(244, 65, 86)','rgb(100, 201, 137)'] barList = [] # List of bar plots to be plotted i = 0 for name in alg_names: y_axis_holder = [] #PROBLEM: The dict entries may be out of order. This would cause the # incorrect entries to be graphed. for metric_dict in y_axis: y_axis_holder.append(metric_dict[name]) barList.append( go.Bar( x=x_axis, y=y_axis_holder, name=name, marker=dict( color=color_list[i], ))) i += 1 layout = go.Layout(barmode='group', legend=dict(x=20.0, y=20.0), title = title) fig = go.Figure(data=barList, layout=layout) return fig
def position_comparison(): plot_layout = go.Layout( title='X position comparison', xaxis={'title': 'Time [s]'}, yaxis={'title': 'X position [m]'} ) plot_data = [] for i, (label, bag_file_name, odometry_topic_name) in enumerate(comparisons): td_visual, td_vicon = load_one_comparison(bag_file_name, odometry_topic_name) plot_data.append( go.Scatter(x=td_visual.col(0)[::4], y=td_visual.col(1)[::4], mode='lines+markers', name=label, marker={'maxdisplayed': 150})) if i == 0: # Only plot ground truth once plot_data.append( go.Scatter(x=td_vicon.col(0)[::20], y=td_vicon.col(1)[::20], mode='lines+markers', name='Truth', marker={'maxdisplayed': 150})) fig = go.Figure(data=plot_data, layout=plot_layout) url = py.plot(fig, filename='vslam_eval_x_pos')
def plot_graph(traces, title): py.sign_in(settings.PLOTLY_USERNAME, settings.PLOTLY_PASSWORD) filename = str(uuid.uuid4()) + ".png" layout = go.Layout(title=title, width=800, height=640) fig = go.Figure(data=traces, layout=layout) # plot_file = offline.plot(fig, show_link=False, auto_open=False, # filename=settings.MEDIA_ROOT + filename, # include_plotlyjs=True) # ghost = Ghost() # page, resources = ghost.open(plot_file) plot_url = py.plot(fig, filename=filename, auto_open=False, file_opt='new') return plot_url + ".png" # return "http://8d30bf7d.ngrok.io/media/" + filename + ".html"
def plotRoadsGraphMapbox(graph,filename): data = [] for u,v in graph.edges(): data.append( go.Scattermapbox( lon = [graph.node[u]['longitude'], graph.node[v]['longitude']], lat = [graph.node[u]['latitude'], graph.node[v]['latitude']], mode = 'lines+markers', line = my_style[graph[u][v]['level']] # marker = dict( # size=4, # opacity=0.7 # ) ), ) x,y = getCentroidFromRoadsGraph(graph) layout = go.Layout( autosize=True, hovermode='closest', showlegend=False, mapbox=dict( accesstoken='pk.eyJ1Ijoic2hhbmdkYWVtb24iLCJhIjoiZjJRcmZGayJ9._dYrpwwYABAtlrxIfXUE1A', style='mapbox://styles/shangdaemon/ciyv9wgdq002e2rmazybmr7g8', bearing=0, center=dict( lat=y, lon=x ), pitch=0, zoom=12 ), ) fig = dict(data=data, layout=layout) plot(fig, filename=filename+'.html', validate=False)
def plotRoadsGraphMap(graph,filename): data = [] for u,v in graph.edges(): data.append( go.Scattermapbox( lon = [graph.node[u]['longitude'], graph.node[v]['longitude']], lat = [graph.node[u]['latitude'], graph.node[v]['latitude']], mode = 'lines+markers', line = my_style[graph[u][v]['level']] # marker = dict( # size=4, # opacity=0.7 # ) ), ) x,y = getCentroidFromRoadsGraph(graph) layout = go.Layout( showlegend=False, geo = dict( showland = True, landcolor = 'rgb(243, 243, 243)', countrycolor = 'rgb(204, 204, 204)', projection=dict( type='conic conformal' ) ), ) fig = dict(data=data, layout=layout) plot(fig, filename=filename+'.html', validate=False)
def create_layout(self): return Layout( title=self.plot_title, xaxis=dict(title='Tijd'), yaxis=dict(title='Kamervragen per week'), margin=Margin(t=20), legend=dict( x=0.01, y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def create_layout(self): return Layout( yaxis=dict(title='Kamervragen per maand'), margin=Margin(t=20, b=30), legend=dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def create_layout(self): return Layout( yaxis=dict(title='Kamervragen per partijzetel per maand', range=[0, 6]), margin=Margin(t=20, b=30), legend=dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def create_layout(self): return Layout( # title="Kamervraag Antwoordtijd vs Tijd", xaxis=dict(title='Kamervraag Ingediend [tijd]'), yaxis=dict(title='Antwoordtijd [dagen]'), autosize=False, width=1000, height=500, margin=Margin(t=20) )
def create_layout(self): return Layout( # title="Kamervragen per Week", xaxis=dict(title='Tijd'), yaxis=dict(title='Zetels per partij'), margin=Margin(t=20), legend=dict( # x=0.01, # y=1, bordercolor='#E2E2E2', bgcolor='#FFFFFF', borderwidth=2 ) )
def barDiv(slope, value, suffix, bar_suffix, bar_format, color, layoutRange): infoText=(str(value) + str(suffix)) tendancy = (slope*timedelta(days=7).total_seconds()) # ToDO: round instead if tendancy > 0: tendancyText="+" tendancyOrigin=0.825 else: tendancyText="" tendancyOrigin=0.675 tendancyText+=str(bar_format % tendancy)+' '+bar_suffix tendancyPosition=tendancyOrigin+((1.2*tendancy)/layoutRange[1]/4) # Bar barChart = go.Bar( x=['tendancy',], y=[float(tendancy),], name="Bar", showlegend=False, hoverinfo="none", marker=dict(color=color), ) # Layout layout = go.Layout( xaxis=dict(showticklabels=False, autotick=False, showgrid=False, zeroline=True, fixedrange=True, domain=[0, 1], ), yaxis=dict(showticklabels=False, autotick=False, showgrid=False, zeroline=False, fixedrange=True, domain=[0.5, 1], range=layoutRange, ), annotations=[ dict(xref='paper', yref='paper', x=0.5, y=0, text=infoText, font=dict(size='20', color='#ffffff'), xanchor='center', yanchor='middle', showarrow=False), dict(xref='paper', yref='paper', x=0.5, y=tendancyPosition, text=tendancyText, font=dict(size='14', color='#ffffff'), xanchor='center', yanchor='middle', showarrow=False), ], height=260, width=120, margin=dict(l=0, r=0, t=40, b=40, autoexpand=False), plot_bgcolor="rgba(0,0,0,0)", paper_bgcolor="rgba(0,0,0,0)" ) # Build HTML div div = plotly.plot(dict(data=[barChart], layout=layout), include_plotlyjs=False, show_link=False, output_type='div') return div #----------------------------------------------------------------------------------------- # Get arguments
def boolean_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].astype(int), 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].astype(int))]) 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, zeroline=False, tickmode="array", tickvals=[0, 1], ticktext=["No", "Yes"] ) ) return Markup(py.plot(go.Figure(data=data, layout=layout), **_DEFAULT_ARGS))
def showTrace(trace, layout=None, title=None): """ Wrapper around plotlys offline .plot() function Parameters ---------- trace : plotly_trace Plotly generated trace to be displayed offline colorize : Bool, optional Toggles bw / colored plot [Default: True] Returns ------- fig : plotly_fig_handle JSON representation of generated figure """ if layout is None: layout = go.Layout( scene=dict( xaxis=dict(range=[-1, 1]), yaxis=dict(range=[-1, 1]), zaxis=dict(range=[-1, 1]), aspectmode='cube' ) ) # Wrap trace in array if needed if not isinstance(trace, list): trace = [trace] fig = go.Figure( data=trace, layout=layout ) if title is not None: fig.layout.update(title=title) filename = title + '.html' else: try: filename = fig.layout.title + '.html' except TypeError: filename = str(current_time()) + '.html' # if colorize: # data[0].autocolorscale = False # data[0].surfacecolor = [0, 0.5, 1] if env_info() == 'jupyter_notebook': plotly_off.init_notebook_mode() plotly_off.iplot(fig) else: plotly_off.plot(fig, filename=filename) return fig
def generatePlot(trace, traceLabels, plotname): data = [trace, traceLabels] layout = go.Layout( margin=dict( l=0, r=0, b=0, t=32, ), title=plotname, scene=dict( xaxis=dict( showgrid=False, showticklabels=False, showspikes=False, showline=False, showaxeslabels=False, zeroline=False, title='', ), yaxis=dict( showgrid=False, showticklabels=False, showspikes=False, showline=False, showaxeslabels=False, zeroline=False, title='', ), zaxis=dict( showgrid=False, showticklabels=False, showspikes=False, showline=False, showaxeslabels=False, zeroline=False, title='', ), ) ) fig = go.Figure(data=data, layout=layout) return py.plot(fig, filename=plotname, auto_open=False)
def _update_graph(map_style, region): dff = dataframe radius_multiplier = {'inner': 1.5, 'outer': 3} layout = go.Layout( title=metadata['title'], autosize=True, hovermode='closest', height=750, font=dict(family=theme['font-family']), margin=go.Margin(l=0, r=0, t=45, b=10), mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=regions[region]['lat'], lon=regions[region]['lon'], ), pitch=0, zoom=regions[region]['zoom'], style=map_style, ), ) data = go.Data([ # outer circles represent magnitude go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['outer'], colorscale=colorscale_magnitude, color=dff['Magnitude'], opacity=1, ), text=dff['Text'], # hoverinfo='text', showlegend=False, ), # inner circles represent depth go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['inner'], colorscale=colorscale_depth, color=dff['Depth'], opacity=1, ), # hovering behavior is already handled by outer circles hoverinfo='skip', showlegend=False ), ]) figure = go.Figure(data=data, layout=layout) return figure
def callbacks(self, app): @app.callback( Output(self.ID, 'figure'), [Input('xaxis-column', 'value'), Input('yaxis-column', 'value'), Input('xaxis-type', 'value'), Input('yaxis-type', 'value'), Input(self.SUBSET_ID, 'value'), Input(UMIsVsGenesGate.ID, 'selectedData') ]) def update_gene_vs_gene_scatter(xaxis_col, yaxis_col, xaxis_type, yaxis_type, group_name, selectedData): """Update the gene vs gene scatter plot""" group_barcodes = self._get_dropdown_barcodes(group_name) # Can't use self.counts[group_barcodes, columns] to index the # SparseDataFrame so select the genes first and then subset on # cells columns = [xaxis_col, yaxis_col] data = pd.DataFrame(self.counts[columns].todense(), index=self.counts.rows, columns=columns) # row = [self.counts._get_row(i) for i in group_barcodes] # self.counts[np.array(group_barcodes)[:, None], columns] group_counts = data.loc[group_barcodes, :] alpha = pd.Series(1.0, index=group_barcodes) hovertext = group_counts[columns].apply( lambda x: '{}: {}, {}'.format(x.name, x[0], x[1]), 1) if selectedData and selectedData['points']: barcodes = {d['customdata'] for d in selectedData['points']} alpha.loc[~alpha.index.isin(barcodes)] = 0.1 hovertext[~hovertext.index.isin(barcodes)] = '' return { 'data': [ go.Scatter(x=group_counts[xaxis_col], y=group_counts[yaxis_col], mode='markers', marker={'opacity': alpha}, hovertext=hovertext.values) ], 'layout': go.Layout( xaxis={'title': xaxis_col + ' ' + group_name, 'type': xaxis_type.lower()}, yaxis={'title': yaxis_col, 'type': yaxis_type.lower(), 'scaleanchor': 'x'}, margin={'l': 40, 'b': 40, 't': 10, 'r': 0}, hovermode='closest', dragmode='select') }
def thread_durations(self): """Returns a pie chart showing grouped thread duration information. A "thread" must consist of more than one email. """ c = self.conn.cursor() c.execute('''SELECT strftime('%s', MAX(`date`)) - strftime('%s', MIN(`date`)) AS duration, COUNT(message_key) AS message_count FROM messages WHERE gmail_labels NOT LIKE '%Chat%' GROUP BY gmail_thread_id HAVING message_count > 1;''') data = {'<= 10 min.': 0, '10 mins - 1 hr.': 0, '1 - 10 hrs.': 0, '10 - 24 hrs.': 0, '1 - 7 days': 0, '1 - 2 weeks': 0, 'more than 2 weeks': 0} for row in c.fetchall(): if row[0] <= 600: data['<= 10 min.'] += 1 elif row[0] <= 3600: data['10 mins - 1 hr.'] += 1 elif row[0] <= 36000: data['1 - 10 hrs.'] += 1 elif row[0] <= 86400: data['10 - 24 hrs.'] += 1 elif row[0] <= 604800: data['1 - 7 days'] += 1 elif row[0] <= 1209600: data['1 - 2 weeks'] += 1 else: data['more than 2 weeks'] += 1 trace = pgo.Pie( labels=data.keys(), values=data.values(), marker=dict( colors=[ self.config.get('color', 'primary'), self.config.get('color', 'secondary'), ] ) ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Thread Durations' del layout_args['xaxis'] del layout_args['yaxis'] layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[trace], layout=layout))
def time_of_day(self): """Returns a graph showing email activity (sent/received) by time of day. """ c = self.conn.cursor() c.execute('''SELECT strftime('%H', `date`) AS hour, COUNT(CASE WHEN `from` LIKE ? THEN 1 ELSE NULL END) AS emails_sent, COUNT(CASE WHEN `from` NOT LIKE ? THEN 1 ELSE NULL END) AS emails_received FROM messages WHERE gmail_labels LIKE '%Chat%' GROUP BY hour ORDER BY hour ASC;''', ('%' + self.owner_email + '%', '%' + self.owner_email + '%')) sent = OrderedDict() sent_total = 0 received = OrderedDict() received_total = 0 for row in c.fetchall(): sent_total += row[1] received_total += row[2] sent[row[0]] = row[1] received[row[0]] = row[2] sent_args = dict( x=sent.keys(), y=sent.values(), name='Emails sent', marker=dict( color=self.config.get('color', 'primary'), ), ) received_args = dict( x=received.keys(), y=received.values(), name='Emails received', marker=dict( color=self.config.get('color', 'secondary') ), ) layout_args = plotly_default_layout_options() layout_args['title'] = 'Activity by Hour of the Day (UTC)' layout_args['xaxis']['title'] = 'Hour of the day (UTC)' layout_args['yaxis']['title'] = 'Number of emails' sent_trace = pgo.Scatter(**sent_args) received_trace = pgo.Scatter(**received_args) layout = pgo.Layout(**layout_args) return plotly_output(pgo.Figure(data=[sent_trace, received_trace], layout=layout))