本文整理汇总了Python中plotly.graph_objs方法的典型用法代码示例。如果您正苦于以下问题:Python plotly.graph_objs方法的具体用法?Python plotly.graph_objs怎么用?Python plotly.graph_objs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类plotly
的用法示例。
在下文中一共展示了plotly.graph_objs方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_chart
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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")
示例2: custom_plot
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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)
示例3: ensure_plotly
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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.")
示例4: bar_plot
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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)
示例5: plot_data_sources_graph
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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)
示例6: plot_graph
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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)
示例7: violin_plot
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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)
示例8: scatter_plot
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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)
示例9: update_graph_scatter
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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')
示例10: update_hist_graph_scatter
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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')
示例11: DrawScatters
# 需要导入模块: import plotly [as 别名]
# 或者: from plotly import graph_objs [as 别名]
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