我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用plotly.plotly()。
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 download_plotlyjs(download_url): warnings.warn(''' `download_plotlyjs` is deprecated and will be removed in the next release. plotly.js is shipped with this module, it is no longer necessary to download this bundle separately. ''', DeprecationWarning) pass
def get_plotlyjs(): path = os.path.join('offline', 'plotly.min.js') plotlyjs = resource_string('plotly', path).decode('utf-8') return plotlyjs
def enable_mpl_offline(resize=False, strip_style=False, verbose=False, show_link=True, link_text='Export to plot.ly', validate=True): """ Convert mpl plots to locally hosted HTML documents. This function should be used with the inline matplotlib backend that ships with IPython that can be enabled with `%pylab inline` or `%matplotlib inline`. This works by adding an HTML formatter for Figure objects; the existing SVG/PNG formatters will remain enabled. (idea taken from `mpld3._display.enable_notebook`) Example:
from plotly.offline import enable_mpl_offline import matplotlib.pyplot as plt enable_mpl_offline() fig = plt.figure() x = [10, 15, 20, 25, 30] y = [100, 250, 200, 150, 300] plt.plot(x, y, "o") fig ``` """ init_notebook_mode() ip = IPython.core.getipython.get_ipython() formatter = ip.display_formatter.formatters['text/html'] formatter.for_type(matplotlib.figure.Figure, lambda fig: iplot_mpl(fig, resize, strip_style, verbose, show_link, link_text, validate))
```
def asset_bubble(output_by_assets): """Creates a crossfilter bokeh plot of results by asset :output_by_assets: Contains output by asset :type output_by_assets: dataframe :returns: :rtype: """ import numpy as np import pandas as pd import plotly.plotly as py import plotly.graph_objs as go df_all = output_by_assets.copy() df = df_all[df_all['asset_category']!='Intellectual Property'].copy() # sort categories df['sort_order'] = df['asset_category'] df['sort_order'].replace(asset_category_order,inplace=True) df.sort_values(by="sort_order",axis=0,ascending=True,inplace=True) df.reset_index(inplace=True) # update asset_category names for better printing df['asset_category'].replace(asset_categories_for_print,inplace=True) df.iplot(kind='bubble', x='metr_c', y='asset_category', size='assets', text='Asset', xTitle='Marginal Effective Tax Rate', yTitle='Asset Category', filename='BubbleChart.png')
def write(timestamp, temperatures): if invalidConfig: if plotly_debugEnabled: plotly_logger.debug('Invalid config, aborting write') return [] debug_message = 'Writing to ' + plugin_name if not plotly_writeEnabled: debug_message += ' [SIMULATED]' plotly_logger.debug(debug_message) debug_text = '%s: ' % timestamp if plotly_writeEnabled: # Stream tokens from plotly tls.set_credentials_file(stream_ids=stream_ids_array) try: if plotly_writeEnabled: py.sign_in(plotly_username, plotly_api_key) for temperature in temperatures: debug_text += "%s (%s A" % (temperature.zone, temperature.actual) if temperature.target is not None: debug_text += ", %s T" % temperature.target debug_text += ') ' if plotly_writeEnabled: if temperature.zone in zones: stream_id = zones[temperature.zone] s = py.Stream(stream_id) s.open() ts = timestamp.strftime('%Y-%m-%d %H:%M:%S') s.write(dict(x=ts, y=temperature.actual)) s.close() else: plotly_logger.debug("Zone %s does not have a stream id, ignoring") except Exception, e: plotly_logger.error("Plot.ly API error - aborting write\n%s", e) if plotly_debugEnabled: plotly_logger.debug(debug_text)
def plot_results(avg, avg_upper, avg_lower): n = len(avg) x =[i+1 for i in range(n+1)] x_rev = x[::-1] y1 = list(avg) y_upper = list(avg_upper) y_lower = list(avg_lower) y_lower = [0,0] + y_lower[::-1] trace1 = Scatter( x=x+x_rev, y=y_upper+y_lower, fill='tozerox', fillcolor='rgba(0,100,80,0.2)', line=Line(color='transparent'), showlegend=False, name='Fair' ) trace2 = Scatter( x=x, y=y1, line=Line(color='rgb(0,100,80)'), mode='lines', name='Fair' ) data = Data([trace1, trace2]) layout = Layout( paper_bgcolor='rgb(255,255,255)', plot_bgcolor='rgb(229,229,229)', xaxis=XAxis( gridcolor='rgb(255,255,255)', range=[1,n+1], showgrid=True, showline=False, showticklabels=True, tickcolor='rgb(127,127,127)', ticks='outside', zeroline=False ), yaxis=YAxis( gridcolor='rgb(255,255,255)', showgrid=True, showline=False, showticklabels=True, tickcolor='rgb(127,127,127)', ticks='outside', zeroline=False ) ) plotly.offline.plot({"data": data, "layout": layout})
def gen_heatmap(model_name): evaluator, valid_stream, ds = build_evaluator(model_name) analysis_path = os.path.join('heatmap_analysis', model_name + ".html") out_file = open(analysis_path, 'w') out_file.write('<html>') out_file.write('<body style="background-color:white">') printed = 0; for batch in valid_stream.get_epoch_iterator(as_dict=True): if batch["context"].shape[1] > 150: continue; evaluator.initialize_aggregators() evaluator.process_batch(batch) analysis_results = evaluator.get_aggregated_values() q_c_attention = analysis_results["question_context_attention"] context_words = [ds.vocab[i]+' '+str(index) for index,i in enumerate(batch["context"][0])] question_words = [str(index)+' '+ ds.vocab[i] for index, i in enumerate(batch["question"][0])] answer_words = [ds.vocab[i] for i in batch["answer"][0]] out_file.write('answer: '+' '.join(answer_words)) out_file.write('<br>') x= context_words y= question_words z = q_c_attention[0] # print z.shape data = [ go.Heatmap(z=z,x=x,y=y,colorscale='Viridis') ] div = plotly.offline.plot(data,auto_open=False, output_type='div') out_file.write(div) out_file.write('<br>') out_file.write('<br>') printed += 1 if printed >= 20: break; out_file.write('</body>') out_file.write('</html>') out_file.close() print "done ;)"