Python plotly.graph_objs() Examples
The following are 15
code examples of plotly.graph_objs().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
plotly
, or try the search function
.
Example #1
Source File: callret_analysis.py From idasec with GNU Lesser General Public License v2.1 | 7 votes |
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")
Example #2
Source File: visualization.py From QCPortal with BSD 3-Clause "New" or "Revised" License | 6 votes |
def custom_plot(data: Any, layout: Any, return_figure=True) -> "plotly.Figure": """A custom plotly plot where the data and layout are pre-specified Parameters ---------- data : Any Plotly data block layout : Any Plotly layout block return_figure : bool, optional Returns the raw plotly figure or not """ check_plotly() import plotly.graph_objs as go figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-bar", return_figure)
Example #3
Source File: notebook_integration.py From adaptive with BSD 3-Clause "New" or "Revised" License | 6 votes |
def ensure_plotly(): global _plotly_enabled try: import plotly if not _plotly_enabled: import plotly.graph_objs import plotly.figure_factory import plotly.offline # This injects javascript and should happen only once plotly.offline.init_notebook_mode() _plotly_enabled = True return plotly except ModuleNotFoundError: raise RuntimeError("plotly is not installed; plotting is disabled.")
Example #4
Source File: visualization.py From QCFractal with BSD 3-Clause "New" or "Revised" License | 6 votes |
def custom_plot(data: Any, layout: Any, return_figure=True) -> "plotly.Figure": """A custom plotly plot where the data and layout are pre-specified Parameters ---------- data : Any Plotly data block layout : Any Plotly layout block return_figure : bool, optional Returns the raw plotly figure or not """ check_plotly() import plotly.graph_objs as go figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-bar", return_figure)
Example #5
Source File: visualization.py From QCPortal with BSD 3-Clause "New" or "Revised" License | 5 votes |
def bar_plot(traces: "List[Series]", title=None, ylabel=None, return_figure=True) -> "plotly.Figure": """Renders a plotly bar plot Parameters ---------- traces : List[Series] A list of bar plots to show, if more than one series the resulting graph will be grouped. title : None, optional The title of the graph ylabel : None, optional The y axis label return_figure : bool, optional Returns the raw plotly figure or not Returns ------- plotly.Figure The requested bar plot. """ check_plotly() import plotly.graph_objs as go data = [go.Bar(x=trace.index, y=trace, name=trace.name) for trace in traces] layout = {} if title: layout["title"] = title if ylabel: layout["yaxis"] = {"title": ylabel} layout = go.Layout(layout) figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-bar", return_figure)
Example #6
Source File: data_source_mapping.py From DeTTECT with GNU General Public License v3.0 | 5 votes |
def plot_data_sources_graph(filename, output_filename): """ Generates a line graph which shows the improvements on numbers of data sources through time. :param filename: the filename of the YAML file containing the data sources administration :param output_filename: the output filename defined by the user :return: """ # pylint: disable=unused-variable my_data_sources, name, platform, exceptions = _load_data_sources(filename) graph_values = [] for t in my_data_sources.values(): if t['date_connected']: yyyymm = t['date_connected'].strftime('%Y-%m') graph_values.append({'date': yyyymm, 'count': 1}) import pandas as pd df = pd.DataFrame(graph_values).groupby('date', as_index=False)[['count']].sum() df['cumcount'] = df['count'].cumsum() if not output_filename: output_filename = 'graph_data_sources' elif output_filename.endswith('.html'): output_filename = output_filename.replace('.html', '') output_filename = get_non_existing_filename('output/' + output_filename, 'html') import plotly import plotly.graph_objs as go plotly.offline.plot( {'data': [go.Scatter(x=df['date'], y=df['cumcount'])], 'layout': go.Layout(title="# of data sources for " + name)}, filename=output_filename, auto_open=False ) print("File written: " + output_filename)
Example #7
Source File: technique_mapping.py From DeTTECT with GNU General Public License v3.0 | 5 votes |
def plot_graph(filename, type_graph, output_filename): """ Generates a line graph which shows the improvements on detections through the time. :param filename: the filename of the YAML file containing the techniques administration :param type_graph: indicates the type of the graph: detection or visibility :param output_filename: the output filename defined by the user :return: """ # pylint: disable=unused-variable my_techniques, name, platform = load_techniques(filename) graph_values = [] for t in my_techniques.values(): for item in t[type_graph]: date = get_latest_date(item) if date: yyyymm = date.strftime('%Y-%m') graph_values.append({'date': yyyymm, 'count': 1}) import pandas as pd df = pd.DataFrame(graph_values).groupby('date', as_index=False)[['count']].sum() df['cumcount'] = df['count'].cumsum() if not output_filename: output_filename = 'graph_' + type_graph elif output_filename.endswith('.html'): output_filename = output_filename.replace('.html', '') output_filename = get_non_existing_filename('output/' + output_filename, 'html') import plotly import plotly.graph_objs as go plotly.offline.plot( {'data': [go.Scatter(x=df['date'], y=df['cumcount'])], 'layout': go.Layout(title="# of %s items for %s" % (type_graph, name))}, filename=output_filename, auto_open=False ) print("File written: " + output_filename)
Example #8
Source File: visualization.py From QCFractal with BSD 3-Clause "New" or "Revised" License | 5 votes |
def bar_plot(traces: "List[Series]", title=None, ylabel=None, return_figure=True) -> "plotly.Figure": """Renders a plotly bar plot Parameters ---------- traces : List[Series] A list of bar plots to show, if more than one series the resulting graph will be grouped. title : None, optional The title of the graph ylabel : None, optional The y axis label return_figure : bool, optional Returns the raw plotly figure or not Returns ------- plotly.Figure The requested bar plot. """ check_plotly() import plotly.graph_objs as go data = [go.Bar(x=trace.index, y=trace, name=trace.name) for trace in traces] layout = {} if title: layout["title"] = title if ylabel: layout["yaxis"] = {"title": ylabel} layout = go.Layout(layout) figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-bar", return_figure)
Example #9
Source File: visualization.py From QCPortal with BSD 3-Clause "New" or "Revised" License | 4 votes |
def violin_plot( traces: "DataFrame", negative: "DataFrame" = None, title=None, points=False, ylabel=None, return_figure=True ) -> "plotly.Figure": """Renders a plotly violin plot Parameters ---------- traces : DataFrame Pandas DataFrame of points to plot, will create a violin plot of each column. negative : DataFrame, optional A comparison violin plot, these columns will present the right hand side. title : None, optional The title of the graph points : None, optional Show points or not, this option is not available for comparison violin plots. ylabel : None, optional The y axis label return_figure : bool, optional Returns the raw plotly figure or not Returns ------- plotly.Figure The requested violin plot. """ check_plotly() import plotly.graph_objs as go data = [] if negative is not None: for trace, side in zip([traces, negative], ["positive", "negative"]): p = {"name": trace.name, "type": "violin", "box": {"visible": True}} p["y"] = trace.stack() p["x"] = trace.stack().reset_index().level_1 p["side"] = side data.append(p) else: for name, series in traces.items(): p = {"name": name, "type": "violin", "box": {"visible": True}} p["y"] = series data.append(p) layout = go.Layout({"title": title, "yaxis": {"title": ylabel}}) figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-violin", return_figure)
Example #10
Source File: visualization.py From QCPortal with BSD 3-Clause "New" or "Revised" License | 4 votes |
def scatter_plot( traces: List[Dict[str, Any]], mode="lines+markers", title=None, ylabel=None, xlabel=None, xline=True, yline=True, custom_layout=None, return_figure=True, ) -> "plotly.Figure": """Renders a plotly scatter plot Parameters ---------- traces : List[Dict[str, Any]] A List of traces to plot, require x and y values mode : str, optional The mode of lines, will not override mode in the traces dictionary title : None, optional The title of the graph ylabel : None, optional The y axis label xlabel : None, optional The x axis label xline : bool, optional Show the x-zeroline yline : bool, optional Show the y-zeroline custom_layout : None, optional Overrides all other layout options return_figure : bool, optional Returns the raw plotly figure or not Returns ------- plotly.Figure The requested scatter plot. """ check_plotly() import plotly.graph_objs as go data = [] for trace in traces: data.append(go.Scatter(**trace)) if custom_layout is None: layout = go.Layout( { "title": title, "yaxis": {"title": ylabel, "zeroline": yline}, "xaxis": {"title": xlabel, "zeroline": xline}, } ) else: layout = go.Layout(**custom_layout) figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-violin", return_figure)
Example #11
Source File: dash_mess.py From socialsentiment with MIT License | 4 votes |
def update_graph_scatter(sentiment_term): try: if sentiment_term: df = pd.read_sql("SELECT sentiment.* FROM sentiment_fts fts LEFT JOIN sentiment ON fts.rowid = sentiment.id WHERE fts.sentiment_fts MATCH ? ORDER BY fts.rowid DESC LIMIT 1000", conn, params=(sentiment_term+'*',)) else: df = pd.read_sql("SELECT * FROM sentiment ORDER BY id DESC, unix DESC LIMIT 1000", conn) df.sort_values('unix', inplace=True) df['date'] = pd.to_datetime(df['unix'], unit='ms') df.set_index('date', inplace=True) init_length = len(df) df['sentiment_smoothed'] = df['sentiment'].rolling(int(len(df)/5)).mean() df = df_resample_sizes(df) X = df.index Y = df.sentiment_smoothed.values Y2 = df.volume.values data = plotly.graph_objs.Scatter( x=X, y=Y, name='Sentiment', mode= 'lines', yaxis='y2', line = dict(color = (app_colors['sentiment-plot']), width = 4,) ) data2 = plotly.graph_objs.Bar( x=X, y=Y2, name='Volume', marker=dict(color=app_colors['volume-bar']), ) return {'data': [data,data2],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]), yaxis=dict(range=[min(Y2),max(Y2*4)], title='Volume', side='right'), yaxis2=dict(range=[min(Y),max(Y)], side='left', overlaying='y',title='sentiment'), title='Live sentiment for: "{}"'.format(sentiment_term), font={'color':app_colors['text']}, plot_bgcolor = app_colors['background'], paper_bgcolor = app_colors['background'], showlegend=False)} except Exception as e: with open('errors.txt','a') as f: f.write(str(e)) f.write('\n')
Example #12
Source File: dash_mess.py From socialsentiment with MIT License | 4 votes |
def update_hist_graph_scatter(sentiment_term): try: if sentiment_term: df = pd.read_sql("SELECT sentiment.* FROM sentiment_fts fts LEFT JOIN sentiment ON fts.rowid = sentiment.id WHERE fts.sentiment_fts MATCH ? ORDER BY fts.rowid DESC LIMIT 10000", conn, params=(sentiment_term+'*',)) else: df = pd.read_sql("SELECT * FROM sentiment ORDER BY id DESC, unix DESC LIMIT 10000", conn) df.sort_values('unix', inplace=True) df['date'] = pd.to_datetime(df['unix'], unit='ms') df.set_index('date', inplace=True) # save this to a file, then have another function that # updates because of this, using intervals to read the file. # https://community.plot.ly/t/multiple-outputs-from-single-input-with-one-callback/4970 # store related sentiments in cache cache.set('related_terms', sentiment_term, related_sentiments(df, sentiment_term), 120) #print(related_sentiments(df,sentiment_term), sentiment_term) init_length = len(df) df['sentiment_smoothed'] = df['sentiment'].rolling(int(len(df)/5)).mean() df.dropna(inplace=True) df = df_resample_sizes(df,maxlen=500) X = df.index Y = df.sentiment_smoothed.values Y2 = df.volume.values data = plotly.graph_objs.Scatter( x=X, y=Y, name='Sentiment', mode= 'lines', yaxis='y2', line = dict(color = (app_colors['sentiment-plot']), width = 4,) ) data2 = plotly.graph_objs.Bar( x=X, y=Y2, name='Volume', marker=dict(color=app_colors['volume-bar']), ) df['sentiment_shares'] = list(map(pos_neg_neutral, df['sentiment'])) #sentiment_shares = dict(df['sentiment_shares'].value_counts()) cache.set('sentiment_shares', sentiment_term, dict(df['sentiment_shares'].value_counts()), 120) return {'data': [data,data2],'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]), # add type='category to remove gaps' yaxis=dict(range=[min(Y2),max(Y2*4)], title='Volume', side='right'), yaxis2=dict(range=[min(Y),max(Y)], side='left', overlaying='y',title='sentiment'), title='Longer-term sentiment for: "{}"'.format(sentiment_term), font={'color':app_colors['text']}, plot_bgcolor = app_colors['background'], paper_bgcolor = app_colors['background'], showlegend=False)} except Exception as e: with open('errors.txt','a') as f: f.write(str(e)) f.write('\n')
Example #13
Source File: visAnnos.py From scMatch with MIT License | 4 votes |
def DrawScatters(savefolder, annoFile, visMethod, cords, annos): import plotly import plotly.graph_objs as go annText = os.path.basename(annoFile).split('.')[0] for kind in ['cell type', 'top sample']: if kind not in annos.columns: continue annotationList = sorted(list(set(annos.ix[:,kind]))) import seaborn as sns colorList = sns.hls_palette(n_colors=len(annotationList)) data = [] annoLen = 0 for annoIdx in range(len(annotationList)): annoNames = annotationList[annoIdx] if len(annoNames) > annoLen: annoLen = len(annoNames) indicesOfAnno = annos[kind]==annoNames text = [] for idx in annos.index[indicesOfAnno]: show_text = '%s: %s, barcode: %s' % (kind, annoNames, idx) text.append(show_text) trace = go.Scatter( x = cords.ix[annos.index[indicesOfAnno],'x'], y = cords.ix[annos.index[indicesOfAnno],'y'], name = annoNames, mode = 'markers', marker=dict( color='rgb(%s, %s, %s)' % colorList[annoIdx], size=5, symbol='circle', line=dict( color='rgb(204, 204, 204)', width=1 ), opacity=0.9 ), text = text, ) data.append(trace) if annoLen < 35: layout = go.Layout(legend=dict(orientation="v"),autosize=True,showlegend=True) else: layout = go.Layout(legend=dict(orientation="v"),autosize=True,showlegend=False) fig = go.Figure(data=data, layout=layout) fn = os.path.join(savefolder, '%s_%s_%s.html' % (annText, kind.replace(' ', '_'), visMethod)) print('##########saving plot: %s' % fn) plotly.offline.plot(fig, filename=fn) #start to visualise test dataset
Example #14
Source File: visualization.py From QCFractal with BSD 3-Clause "New" or "Revised" License | 4 votes |
def violin_plot( traces: "DataFrame", negative: "DataFrame" = None, title=None, points=False, ylabel=None, return_figure=True ) -> "plotly.Figure": """Renders a plotly violin plot Parameters ---------- traces : DataFrame Pandas DataFrame of points to plot, will create a violin plot of each column. negative : DataFrame, optional A comparison violin plot, these columns will present the right hand side. title : None, optional The title of the graph points : None, optional Show points or not, this option is not available for comparison violin plots. ylabel : None, optional The y axis label return_figure : bool, optional Returns the raw plotly figure or not Returns ------- plotly.Figure The requested violin plot. """ check_plotly() import plotly.graph_objs as go data = [] if negative is not None: for trace, side in zip([traces, negative], ["positive", "negative"]): p = {"name": trace.name, "type": "violin", "box": {"visible": True}} p["y"] = trace.stack() p["x"] = trace.stack().reset_index().level_1 p["side"] = side data.append(p) else: for name, series in traces.items(): p = {"name": name, "type": "violin", "box": {"visible": True}} p["y"] = series data.append(p) layout = go.Layout({"title": title, "yaxis": {"title": ylabel}}) figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-violin", return_figure)
Example #15
Source File: visualization.py From QCFractal with BSD 3-Clause "New" or "Revised" License | 4 votes |
def scatter_plot( traces: List[Dict[str, Any]], mode="lines+markers", title=None, ylabel=None, xlabel=None, xline=True, yline=True, custom_layout=None, return_figure=True, ) -> "plotly.Figure": """Renders a plotly scatter plot Parameters ---------- traces : List[Dict[str, Any]] A List of traces to plot, require x and y values mode : str, optional The mode of lines, will not override mode in the traces dictionary title : None, optional The title of the graph ylabel : None, optional The y axis label xlabel : None, optional The x axis label xline : bool, optional Show the x-zeroline yline : bool, optional Show the y-zeroline custom_layout : None, optional Overrides all other layout options return_figure : bool, optional Returns the raw plotly figure or not Returns ------- plotly.Figure The requested scatter plot. """ check_plotly() import plotly.graph_objs as go data = [] for trace in traces: data.append(go.Scatter(**trace)) if custom_layout is None: layout = go.Layout( { "title": title, "yaxis": {"title": ylabel, "zeroline": yline}, "xaxis": {"title": xlabel, "zeroline": xline}, } ) else: layout = go.Layout(**custom_layout) figure = go.Figure(data=data, layout=layout) return _configure_return(figure, "qcportal-violin", return_figure)