def test_update_dict(): title = 'this' fig = Figure() fig.update(layout=Layout(title=title)) assert fig == Figure(layout=Layout(title=title)) fig['layout'].update(xaxis=XAxis()) assert fig == Figure(layout=Layout(title=title, xaxis=XAxis()))
def test_nested_frames(self): with self.assertRaisesRegexp(exceptions.PlotlyDictKeyError, 'frames'): Figure({'frames': [{'frames': []}]}) figure = Figure() figure.frames = [{}] with self.assertRaisesRegexp(exceptions.PlotlyDictKeyError, 'frames'): figure.frames[0].frames = []
def test_update_list_empty(self): trace1 = Scatter(x=[1, 2, 3], y=[2, 1, 2]) trace2 = Scatter(x=[1, 2, 3], y=[3, 2, 1]) fig = Figure([trace1, trace2]) fig.update([]) d1, d2 = strip_dict_params(fig.data[0], Scatter(x=[1, 2, 3], y=[2, 1, 2])) assert d1 == d2 d1, d2 = strip_dict_params(fig.data[1], Scatter(x=[1, 2, 3], y=[3, 2, 1])) assert d1 == d2
def test_update_dict(self): title = 'this' fig = Figure() update_res1 = fig.update(layout=Layout(title=title)) assert fig == Figure(layout=Layout(title=title)) update_res2 = fig['layout'].update(xaxis=XAxis()) assert fig == Figure(layout=Layout(title=title, xaxis=XAxis())) assert update_res1 is fig assert update_res2 is fig.layout
def test_to_string(): fig = Figure( data=Data([ Scatter( x=[1, 2, 3, 4], y=[10, 15, 13, 17] ), Scatter( x=[1, 2, 3, 4], y=[16, 5, 11, 9] ) ]), layout=Layout( autosize=False, width=500, height=500, margin=Margin( l=65, r=50, b=65, t=65 ) ) ) fig_string = fig.to_string(pretty=False) comp_string = ('Figure(\n' ' data=Data([\n' ' Scatter(\n' ' x=[1, 2, 3, 4],\n' ' y=[10, 15, 13, 17]\n' ' ),\n' ' Scatter(\n' ' x=[1, 2, 3, 4],\n' ' y=[16, 5, 11, 9]\n' ' )\n' ' ]),\n' ' layout=Layout(\n' ' autosize=False,\n' ' width=500,\n' ' height=500,\n' ' margin=Margin(\n' ' l=65,\n' ' r=50,\n' ' b=65,\n' ' t=65\n' ' )\n' ' )\n' ')') assert fig_string == comp_string
def graph_military_spending_over_time(): #Generate scatter plots for each country data = [] with open('data/SIPRI-Milex-data-1988-2015-cleaned-current-usd.csv' ) as current_usd: reader = csv.reader(current_usd) headers = next(reader, None) for row in reader: #Data unavailable, or country didn't exist at the time if ('. .' in row[13:] or 'xxx' in row[13:]): continue trace = Scatter(x=headers[13:], y=row[13:], name=row[0], fill='tonexty', line=dict(width=.5), mode='lines', textfont=dict(family='sans serif', size=30, color='#ff7f0e')) data.append(trace) #Sort scatter plots by countries with highest expenditures in 2015 data = sorted(data, key=lambda trace: float(trace.y[-1])) #Layout taken from https://plot.ly/python/figure-labels/ layout = Layout( title='Discretionary Military Spending 2000-2015', xaxis=dict(title='Year', titlefont=dict(family='Courier New, monospace', size=26, color='#7f7f7f')), yaxis=dict(title='Millions of 2015 US dollars', titlefont=dict(family='Courier New, monospace', size=26, color='#7f7f7f')), annotations=[ dict(x=2009, y=668567, xref='x', yref='y', text='Obama Takes Office; deployments in Iraq winding down', showarrow=True, arrowhead=7, ax=-120, ay=-40), dict(x=2003, y=415223, xref='x', yref='y', text='Beginning of Iraq War', showarrow=True, arrowhead=7, ax=-20, ay=-40), dict(x=2011, y=711338, xref='x', yref='y', text='Official end of Iraq War', showarrow=True, arrowhead=7, ax=0, ay=-25), dict(x=2001, y=312743, xref='x', yref='y', text='9/11; Beginning of War in Afghanistan', showarrow=True, arrowhead=7, ax=-20, ay=-40), dict(x=2014, y=609914, xref='x', yref='y', text='Official End of War in Afghanistan', showarrow=True, arrowhead=7, ax=20, ay=-40) ]) fig = Figure(data=data[len(data) - 15:], layout=layout) plot(fig, filename="images/military-spending-over-time")
layout = Layout( yaxis=YAxis( domain=[0, 0.33] ), legend=Legend( traceorder='reversed' ), yaxis2=YAxis( domain=[0.33, 0.66] ), yaxis3=YAxis( domain=[0.66, 1] ) ) fig = Figure(data=my_data, layout=layout) py.iplot(fig) # Then maybe I want to edit it quickly with a GUI, without coding. I click through to the graph in the "data and graph" link, fork my own copy, and can switch between graph types, styling options, and more. # In[15]: Image(url = 'http://i.imgur.com/rHP53Oz.png') # Now, having re-styled it, we can call the graph back into the NB, and if we want, get the figure information for the new, updated graph. The graphs below are meant to show the flexibility available to you in styling from the GUI. # In[16]:
def fig2(): # (!) Set 'size' values to be proportional to rendered area, # instead of diameter. This makes the range of bubble sizes smaller sizemode = 'area' # (!) Set a reference for 'size' values (i.e. a population-to-pixel scaling). # Here the max bubble area will be on the order of 100 pixels sizeref = df['Population'].max() / 1e2 ** 2 colors = { 'Asia': "rgb(255,65,54)", 'Europe': "rgb(133,20,75)", 'Africa': "rgb(0,116,217)", 'North America': "rgb(255,133,27)", 'South America': "rgb(23,190,207)", 'Antarctica': "rgb(61,153,112)", 'Oceania': "rgb(255,220,0)", } # Define a hover-text generating function (returns a list of strings) def make_text(X): return 'Country: %s\ <br>Life Expectancy: %s years\ <br>Population: %s million' \ % (X['Name'], X['LifeExpectancy'], X['Population'] / 1e6) # Define a trace-generating function (returns a Scatter object) def make_trace(X, continent, sizes, color): return Scatter( x=X['GNP'], # GDP on the x-xaxis y=X['LifeExpectancy'], # life Exp on th y-axis name=continent, # label continent names on hover mode='markers', # (!) point markers only on this plot text=X.apply(make_text, axis=1).tolist(), marker=Marker( color=color, # marker color size=sizes, # (!) marker sizes (sizes is a list) sizeref=sizeref, # link sizeref sizemode=sizemode, # link sizemode opacity=0.6, # (!) partly transparent markers line=Line(width=3, color="white") # marker borders ) ) # Initialize data object data = Data() # Group data frame by continent sub-dataframe (named X), # make one trace object per continent and append to data object for continent, X in df.groupby('Continent'): sizes = X['Population'] # get population array color = colors[continent] # get bubble color data.append( make_trace(X, continent, sizes, color) # append trace to data object ) # Set plot and axis titles title = "Life expectancy vs GNP from MySQL world database (bubble chart)" x_title = "Gross National Product" y_title = "Life Expectancy [in years]" # Define a dictionary of axis style options axis_style = dict( type='log', zeroline=False, # remove thick zero line gridcolor='#FFFFFF', # white grid lines ticks='outside', # draw ticks outside axes ticklen=8, # tick length tickwidth=1.5 # and width ) # Make layout object layout = Layout( title=title, # set plot title plot_bgcolor='#EFECEA', # set plot color to grey hovermode="closest", xaxis=XAxis( axis_style, # add axis style dictionary title=x_title, # x-axis title range=[2.0, 7.2], # log of min and max x limits ), yaxis=YAxis( axis_style, # add axis style dictionary title=y_title, # y-axis title ) ) # Make Figure object fig = Figure(data=data, layout=layout) # (@) Send to Plotly and show in notebook py.iplot(fig, filename='s3_life-gdp')
def render_graph(graph_data: dict): # convert dates to timestamp, to the x axis can be considered a real date when = [(int(x.strftime('%s')) * 1000) for x in graph_data['info_date_when']] trace1 = Scatter(x=when, y=graph_data['info_tweets_per_day'], mode='markers', marker={ 'size': 25, 'color': 'rgba(191, 63, 63, .9)', 'line': { 'width': 3, } }, name='tweets', yaxis='y2') # druhý graf, čtverečky trace2 = Scatter(x=when, y=graph_data['info_likes_number'], mode='markers', marker={ 'symbol': 'square', 'size': 15, 'color': 'rgba(213, 143, 143, .9)', 'line': { 'width': 2, } }, name='likes', yaxis='y2') # treti graf, souvisla cara trace3 = Scatter( x=when, y=graph_data['info_followers_per_day'], mode='lines', name='followers', ) data = [trace1, trace2, trace3] min_followers = min(graph_data['info_followers_per_day']) max_followers = max(graph_data['info_followers_per_day']) min_followers = floor(min_followers / 100) * 100 # round to bottom 100 max_followers = ceil(max_followers / 100) * 100 # round to upper 100 max_tweets_likes = max(graph_data['info_tweets_per_day'] + graph_data['info_likes_number']) yaxis2 = dict( title='tweets & likes', showline=True, zeroline=False, titlefont=dict(color='rgb(191, 63, 63)'), tickfont=dict(color='rgb(191, 63, 63)'), overlaying='y', side='right', ) if max_tweets_likes < 20: # use linear axis yaxis2.update( dict( range=[0, max(5, max_tweets_likes)], type='linear', )) else: # use logarithmic axis yaxis2.update(dict( type='log', autorange=True, )) layout = Layout(title='Twitter Statistics for {}'.format( graph_data['user']['screen_name']), xaxis=dict( title='dates', type='date', showline=True, ), yaxis=dict(title='followers', range=[min_followers, max_followers], zeroline=True, showline=True, titlefont=dict(color='rgb(63, 191, 63)'), tickfont=dict(color='rgb(63, 191, 63)')), yaxis2=yaxis2) ''' # tohle by vykreslilo grafy pod sebou data = tools.make_subplots(rows=1, cols=2) data.append_trace(trace1, 1, 1) data.append_trace(trace2, 1, 2) ''' fig = Figure(data=data, layout=layout) plotly.offline.plot(fig)
def test_instantiation(self): native_figure = {'data': [], 'layout': {}, 'frames': []} Figure(native_figure) Figure()
def visualize_graph(graph: a3_part1.Graph, layout: str = 'spring_layout', max_vertices: int = 5000, output_file: str = '') -> None: """Use plotly and networkx to visualize the given graph. Optional arguments: - layout: which graph layout algorithm to use - max_vertices: the maximum number of vertices that can appear in the graph - output_file: a filename to save the plotly image to (rather than displaying in your web browser) """ graph_nx = graph.to_networkx(max_vertices) pos = getattr(nx, layout)(graph_nx) x_values = [pos[k][0] for k in graph_nx.nodes] y_values = [pos[k][1] for k in graph_nx.nodes] labels = list(graph_nx.nodes) kinds = [graph_nx.nodes[k]['kind'] for k in graph_nx.nodes] colours = [ BOOK_COLOUR if kind == 'book' else USER_COLOUR for kind in kinds ] x_edges = [] y_edges = [] for edge in graph_nx.edges: x_edges += [pos[edge[0]][0], pos[edge[1]][0], None] y_edges += [pos[edge[0]][1], pos[edge[1]][1], None] trace3 = Scatter( x=x_edges, y=y_edges, mode='lines', name='edges', line=dict(color=LINE_COLOUR, width=1), hoverinfo='none', ) trace4 = Scatter(x=x_values, y=y_values, mode='markers', name='nodes', marker=dict(symbol='circle-dot', size=5, color=colours, line=dict(color=VERTEX_BORDER_COLOUR, width=0.5)), text=labels, hovertemplate='%{text}', hoverlabel={'namelength': 0}) data1 = [trace3, trace4] fig = Figure(data=data1) fig.update_layout({'showlegend': False}) fig.update_xaxes(showgrid=False, zeroline=False, visible=False) fig.update_yaxes(showgrid=False, zeroline=False, visible=False) if output_file == '': fig.show() else: fig.write_image(output_file)
if __name__ == "__main__": print("Streaming to Plotly each {0} seconds.".format(STREAMING_PERIOD)) stream = None try: radiationWatch = RadiationWatch(24, 23).setup() py.sign_in(USERNAME, API_KEY) url = py.plot( Figure( layout=Layout( title=PLOT_TITLE, xaxis=dict(title="Timestamp"), yaxis=dict(title="Dose (uSv/h)"), ), data=Data([ Scatter( x=[], y=[], mode="lines", stream=Stream(token=STREAMING_TOKEN), ) ]), ), filename=PLOT_TITLE, ) print("Plotly graph URL: {0}".format(url)) stream = py.Stream(STREAMING_TOKEN) stream.open() while 1: readings = radiationWatch.status() x = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
return Scatter(x=xaxis, y=df[arg], mode='lines', name=arg) #position data leftPathPos = data('leftPathPos') leftEncoder = data('leftEncoder') rightPathPos = data('rightPathPos') rightEncoder = data('rightEncoder') #velocity data leftPathVel = data('leftPathVel') leftEncoderVel = data('leftEncoderVel') rightPathVel = data('rightPathVel') rightEncoderVel = data('rightEncoderVel') #heading data pathHdg = data('pathHdg') gyroYaw = data('gyroYaw') #set up which data should be graphed together pos = Figure(data=[leftPathPos, leftEncoder, rightPathPos, rightEncoder], layout=layout) vel = Figure(data=[leftPathVel, leftEncoderVel, rightPathVel, rightEncoderVel], layout=layout) hdg = Figure(data=[pathHdg, gyroYaw], layout=layout) #graph data py.offline.plot(pos, filename="pos.html") py.offline.plot(vel, filename="vel.html") py.offline.plot(hdg, filename="hdg.html")
name='top 10 TFs with p-value < 0.05', mode='markers', marker=dict(size=9, opacity=0.8), textfont=dict(family='sans serif', size=11, color='black'), text=list( map(lambda x: "%s\n%s" % ('CistromeDB:', x), final_top.loc[:, 'name_y'])), hoverinfo='text', textposition='top right') layout = Layout( title=title, xaxis=dict(title='-log10(p-value) of Gene Set 1' if labels1.strip() == '' else '-log10(p-value) of %s' % labels1, showgrid=False, titlefont=dict(family='Arial', size=20), rangemode='tozero', range=[0, xlim]), yaxis=dict(title='-log10(p-value) of Gene Set 2' if labels2.strip() == '' else '-log10(p-value) of %s' % labels2, showgrid=False, titlefont=dict(family='Arial', size=20), rangemode='tozero', range=[0, ylim]), hovermode='closest', width=850, height=650) fig = Figure(data=[top_trace0, trace1], layout=layout) plot(fig, filename='%s.html' % prefix, show_link=False, auto_open=False)
# 1000 objects # 5 possible features sim5 = [1, 1, 0.992, 0.875, 0.495, 0.162, 0.029, 0.005, 0.001] # From simulations ideal5 = [ 1.0, 1.0, 0.999425, 0.958525, 0.610675, 0.21245, 0.04685, 0.008075, 0.001 ] # Simulations showed this is no better than chance bof5 = [0.001] * 9 # 50 possible features (not used in the CNS submission) sim50 = [1.0, 1.0, 1.0, 0.998, 0.939, 0.456, 0.086, 0.0, 0.001] ideal50 = [1, 1, 1, 1, 1, 0.999775, 0.907775, 0.074875, 0.001] bof50 = [1, 0.9996, 0.980875, 0.782, 0.347525, 0.0958, 0.0231, 0.0048, 0.001] fig = Figure( data=[ getPlot(bof5, "triangle-up-open", "dash", "5 (BOF)"), getPlot(sim5, "circle", "solid", "5"), getPlot(ideal5, "square-open", "dash", "5 (Ideal)"), #getPlot(sim50, "square-open", "dash", "50"), #getPlot(ideal50, "circle", "dash", "50 (Ideal)"), #getPlot(bof50, "triangle-up", "dash", "50 (BOF)"), ], layout=layout, ) signin() py.image.save_as(fig, "accuracy_plot.pdf", width=700, height=400)
def show_plot(data, title, filename='plot.html'): layout_comp = Layout(title=title) fig_comp = Figure(data=data, layout=layout_comp) plotly.offline.plot(fig_comp, filename=filename)
def _set_axis(self,traces,on=None,side='right',title=''): """ Sets the axis in which each trace should appear If the axis doesn't exist then a new axis is created Parameters: ----------- traces : list(str) List of trace names on : string The axis in which the traces should be placed. If this is not indicated then a new axis will be created side : string Side where the axis will be placed 'left' 'right' title : string Sets the title of the axis Applies only to new axis """ fig={} fig_cpy=fig_to_dict(self).copy() fig['data']=fig_cpy['data'] fig['layout']=fig_cpy['layout'] fig=Figure(fig) traces=make_list(traces) def update_data(trace,y): anchor=fig.axis['def'][y]['anchor'] if 'anchor' in fig.axis['def'][y] else 'x1' idx=fig.trace_dict[trace] if isinstance(trace,str) else trace fig['data'][idx]['xaxis']=anchor fig['data'][idx]['yaxis']=y for trace in traces: if on: if on not in fig.axis['def']: raise Exception('"on" axis does not exists: {0}'.format(on)) update_data(trace,y=on) else: curr_x,curr_y=fig.axis['ref'][trace] domain='[0.0, 1.0]' if 'domain' not in fig.axis['def'][curr_y] else str(fig.axis['def'][curr_y]['domain']) try: new_axis=fig.axis['dom']['y'][domain][side] except KeyError: axis=fig.axis['def'][curr_y].copy() ### check overlaying values axis.update(title=title,overlaying=curr_y,side=side,anchor=curr_x) axis_idx=str(fig.axis['len']['y']+1) fig['layout']['yaxis{0}'.format(axis_idx)]=axis new_axis='y{0}'.format(axis_idx) update_data(trace,y=new_axis) for k in list(fig.axis['def'].keys()): id='{0}axis{1}'.format(k[0],k[-1:]) if k not in fig.axis['ref_axis']: try: del fig['layout'][id] except KeyError: pass return fig
def civilian_agenda_item_costs(): #Data for policies and associated costs; #data is in absolute number of dollars data = [("Discretionary Military Spending FY 2000", 301700000000), ("Difference from FY'00 to FY'15", 312700000000), ("Est. Cost of<br>Free Education<br> circa 2014", 65130000000), ("Annualized Cost of<br>Affordable<br>Care Act<br>FY'16", 112500000000), ("DoE<br>Clean<br>Energy<br>R&D<br>FY'17", 12600000000), ("US Foreign Aid<br>Allocation<br>FY'17", 50100000000), ("Est. Cost of<br>the Boarder<br>Wall", 21600000000), ("NASA's<br>FY'16<br>Budget", 19730000000)] for x in range(len(data)): data[x] = (data[x][0] + '<br>${:,}B.'.format(int(data[x][1] / 1000000000)), data[x][1]) #colors taken from colorbrewer2.org colors = [ 'rgb(213,62,79)', 'rgb(252,141,89)', 'rgb(254,224,139)', 'rgb(255,255,191)', 'rgb(230,245,152)', 'rgb(153,213,148)', 'rgb(50,136,189)' ] #Squarify data x = 0 y = 0 width = 100 height = 100 normed = squarify.normalize_sizes([tup[1] for tup in data], width, height) rects = squarify.squarify(normed, x, y, width, height) #Generate treemap (taken directly from https://plot.ly/python/treemaps/) shapes = [] annotations = [] color_counter = 6 policy_counter = 0 for r in rects: shapes.append( dict(type='rect', x0=r['x'], y0=r['y'], x1=r['x'] + r['dx'], y1=r['y'] + r['dy'], line=dict(width=2), fillcolor=colors[color_counter])) annotations.append( dict(x=r['x'] + (r['dx'] / 2), y=r['y'] + (r['dy'] / 2), text=data[policy_counter][0], font=dict(family='Courier New, monospace', size=15, color='#000000'), showarrow=False)) color_counter += 1 policy_counter += 1 if color_counter >= len(colors): color_counter = 0 # For hover text trace = Scatter( x=[r['x'] + (r['dx'] / 2) for r in rects], y=[r['y'] + (r['dy'] / 2) for r in rects], text=['${:,.2f}'.format(tup[1]) for tup in data], mode='text', ) layout = dict(height=950, width=950, shapes=shapes, annotations=annotations, hovermode='closest', title='Policy Costs vs. Military Spending', font=dict(family='Courier New, monospace', size=24, color='#000000')) #Plot treemap fig = Figure(data=[trace], layout=layout) plot(fig, filename="images/policy-spending-treemap")
def test_get_subplot(self): # Make Figure with subplot types fig = subplots.make_subplots( rows=4, cols=2, specs=[[{}, {'secondary_y': True}], [{'type': 'polar'}, {'type': 'ternary'}], [{'type': 'scene'}, {'type': 'geo'}], [{'type': 'domain', 'colspan': 2}, None]] ) fig.add_scatter(y=[2, 1, 3], row=1, col=1) fig.add_scatter(y=[2, 1, 3], row=1, col=2) fig.add_scatter(y=[1, 3, 2], row=1, col=2, secondary_y=True) fig.add_trace(go.Scatterpolar( r=[2, 1, 3], theta=[20, 50, 125]), row=2, col=1) fig.add_traces([go.Scatterternary(a=[.2, .1, .3], b=[.4, .6, .5])], rows=[2], cols=[2]) fig.add_scatter3d(x=[2, 0, 1], y=[0, 1, 0], z=[0, 1, 2], mode='lines', row=3, col=1) fig.add_scattergeo(lat=[0, 40], lon=[10, 5], mode='lines', row=3, col=2) fig.add_parcats( dimensions=[ {'values': ['A', 'A', 'B', 'A', 'B']}, {'values': ['a', 'a', 'a', 'b', 'b']}, ], row=4, col=1) fig.update_traces(uid=None) fig.update(layout_height=1200) # Check expected = Figure({ 'data': [ {'type': 'scatter', 'xaxis': 'x', 'y': [2, 1, 3], 'yaxis': 'y'}, {'type': 'scatter', 'xaxis': 'x2', 'y': [2, 1, 3], 'yaxis': 'y2'}, {'type': 'scatter', 'xaxis': 'x2', 'y': [1, 3, 2], 'yaxis': 'y3'}, {'r': [2, 1, 3], 'subplot': 'polar', 'theta': [20, 50, 125], 'type': 'scatterpolar'}, {'a': [0.2, 0.1, 0.3], 'b': [0.4, 0.6, 0.5], 'subplot': 'ternary', 'type': 'scatterternary'}, {'mode': 'lines', 'scene': 'scene', 'type': 'scatter3d', 'x': [2, 0, 1], 'y': [0, 1, 0], 'z': [0, 1, 2]}, {'geo': 'geo', 'lat': [0, 40], 'lon': [10, 5], 'mode': 'lines', 'type': 'scattergeo'}, {'dimensions': [{'values': ['A', 'A', 'B', 'A', 'B']}, {'values': ['a', 'a', 'a', 'b', 'b']}], 'domain': {'x': [0.0, 0.9400000000000001], 'y': [0.0, 0.19375]}, 'type': 'parcats'}], 'layout': { 'geo': {'domain': {'x': [0.5700000000000001, 0.9400000000000001], 'y': [0.26875, 0.4625]}}, 'height': 1200, 'polar': {'domain': {'x': [0.0, 0.37], 'y': [0.5375, 0.73125]}}, 'scene': {'domain': {'x': [0.0, 0.37], 'y': [0.26875, 0.4625]}}, 'ternary': {'domain': {'x': [0.5700000000000001, 0.9400000000000001], 'y': [0.5375, 0.73125]}}, 'xaxis': {'anchor': 'y', 'domain': [0.0, 0.37]}, 'xaxis2': {'anchor': 'y2', 'domain': [0.5700000000000001, 0.9400000000000001]}, 'yaxis': {'anchor': 'x', 'domain': [0.80625, 1.0]}, 'yaxis2': {'anchor': 'x2', 'domain': [0.80625, 1.0]}, 'yaxis3': {'anchor': 'x2', 'overlaying': 'y2', 'side': 'right'}} }) expected.update_traces(uid=None) # Make sure we have expected starting figure self.assertEqual(fig, expected) # (1, 1) subplot = fig.get_subplot(1, 1) self.assertEqual( subplot, SubplotXY( xaxis=fig.layout.xaxis, yaxis=fig.layout.yaxis)) # (1, 2) Primary subplot = fig.get_subplot(1, 2) self.assertEqual( subplot, SubplotXY( xaxis=fig.layout.xaxis2, yaxis=fig.layout.yaxis2)) # (1, 2) Primary subplot = fig.get_subplot(1, 2, secondary_y=True) self.assertEqual( subplot, SubplotXY( xaxis=fig.layout.xaxis2, yaxis=fig.layout.yaxis3)) # (2, 1) subplot = fig.get_subplot(2, 1) self.assertEqual( subplot, fig.layout.polar) # (2, 2) subplot = fig.get_subplot(2, 2) self.assertEqual( subplot, fig.layout.ternary) # (3, 1) subplot = fig.get_subplot(3, 1) self.assertEqual( subplot, fig.layout.scene) # (3, 2) subplot = fig.get_subplot(3, 2) self.assertEqual( subplot, fig.layout.geo) # (4, 1) subplot = fig.get_subplot(4, 1) domain = fig.data[-1].domain self.assertEqual( subplot, SubplotDomain(x=domain.x, y=domain.y))
def visual(): data = pd.read_csv('log_data/NEO_270619_01_25_04.csv') data['Date'] = pd.to_datetime(data['Date']) # startDate = data.iloc[0].Date # endDate = data.iloc[-1].Date # # # start = int(datetime.timestamp(startDate)) * 1000 + (8*60*60*1000) # end = int(datetime.timestamp(endDate)) * 1000 + (8*60*60*1000) # # # end = '1561702500000' # # getData('NEOUSDT',Client.KLINE_INTERVAL_15MINUTE,start=start,end=end) # exit() klines = pd.read_csv('260619_to_280619_analysis/NEOUSDT_15m.csv') buys = {} buys['date'] = [] buys['price'] = [] buys['target'] = [] buys['exit'] = [] sells = {} sells['date'] = [] sells['price'] = [] prices = {} prices['date'] = [] prices['price'] = [] for i, r in data.iterrows(): prices['date'].append(r['Date']) prices['price'].append(r['Current Price']) if not pd.isna(r['Open Phase Exited']): buys['date'].append(r['Date']) buys['price'].append(r['Buy Price']) buys['target'].append(data.iloc[i + 1]['Target']) buys['exit'].append(data.iloc[i + 1]['Drop Threshold']) if not pd.isna(r['Mini Sell Price']): sells['date'].append(r['Date']) sells['price'].append(r['Mini Sell Price']) a = Candlestick(x=klines.DateTime, open=klines.open, high=klines.high, low=klines.low, close=klines.close) bolliDate = [] bolliLow = [] for i, r in klines.iterrows(): if i < 8: continue bolliDate.append(r.DateTime) bolliLow.append(bollingerLow(klines.iloc[i - 5:i].close)) bolliData = Scatter(name='Bolli', x=bolliDate, y=bolliLow, marker=dict(color='navy', size=4)) priceData = Scatter(name='Current Price', x=prices['date'], mode='lines', y=prices['price'], marker=dict(color='grey', size=10, symbol='star')) targetData = Scatter(name='target', x=buys['date'], y=buys['target'], mode='markers', marker=dict(symbol='triangle-up', color='blue', size=4)) # miniTargetData = Scatter(name='miniTarget',x=miniTargetDate,y=miniTargetList,mode='markers',marker=dict(symbol='triangle-up',color='pink',size=3)) # buyData = Scatter(name='Buy', mode='markers', marker=dict(symbol='circle-open-dot', color='royalblue', size=14), x=buys['date'], y=buys['price']) sellData = Scatter(name='Sell', mode='markers', marker=dict(symbol='star', color='black', size=14), x=sells['date'], y=sells['price']) # miniSellData = Scatter(name='miniSell',mode='markers', marker=dict(symbol='circle-open-dot',color='darkgreen', size=10), x=miniSellDate, y=miniSellPrice) # # buyStopData = Scatter(name='buyStop',mode='markers', marker=dict(symbol='diamond',color='black', size=7), x=buyOrderDate, y=buyOrderStop) # buyLimitData = Scatter(name='buyLimit',mode='markers', marker=dict(symbol='diamond-open',color='black', size=7), x=buyOrderDate, y=buyOrderLimit) # exitData = Scatter(name='exit', mode='markers', marker=dict(symbol='diamond', color='orange', size=7), x=buys['date'], y=buys['exit']) # sellLimitData = Scatter(name='sellLimit',mode='markers', marker=dict(symbol='diamond-open',color='orange', size=7), x=sellOrderDate, # y=sellOrderLimit) # # miniSellStopData = Scatter(name='miniSellStop',mode='markers', marker=dict(symbol='diamond',color='red', size=7), x=miniSellOrderDate, # y=miniSellOrderStop) # miniSellLimitData = Scatter(name='miniSellLimit',mode='markers', marker=dict(symbol='diamond-open',color='red', size=7), x=miniSellOrderDate, # y=miniSellOrderLimit) # # cancelData = Scatter(name='cancel',mode='markers', marker=dict(color='grey', size=7,symbol='cross'), x=cancelDate, y=cancelPrice) # majorFig = Figure(data=[ a, priceData, bolliData, targetData, buyData, exitData, sellData ], layout=Layout(xaxis=dict( rangeslider=dict(visible=False), showgrid=True, ))) print('printing graph...') plotly.offline.plot( majorFig, # show_link=False, # # output_type='div', # include_plotlyjs=False, # filename='charts//'+coin+'_'+str(seed)+'_'+ interval+ '_'+datetime.utcnow().strftime("%d%m%y_%H:%M:%S")+'.html', auto_open=True, config={ 'displaylogo': False, 'modeBarButtonsToRemove': [ 'sendDataToCloud', 'select2d', 'zoomIn2d', 'zoomOut2d', 'resetScale2d', 'hoverCompareCartesian', 'lasso2d' ], 'displayModeBar': True })
def draw_traces(traces, on_map=False, map_style='basic', showlegend=True, figsize=1, aspectratio='auto'): """ plots all the traces (which can be created using :func:`create_bus_trace`, :func:`create_line_trace`, :func:`create_trafo_trace`) to PLOTLY (see https://plot.ly/python/) INPUT: **traces** - list of dicts which correspond to plotly traces generated using: `create_bus_trace`, `create_line_trace`, `create_trafo_trace` OPTIONAL: **on_map** (bool, False) - enables using mapbox plot in plotly **map_style** (str, 'basic') - enables using mapbox plot in plotly - 'streets' - 'bright' - 'light' - 'dark' - 'satellite' **showlegend** (bool, 'True') - enables legend display **figsize** (float, 1) - aspectratio is multiplied by it in order to get final image size **aspectratio** (tuple, 'auto') - when 'auto' it preserves original aspect ratio of the network geodata any custom aspectration can be given as a tuple, e.g. (1.2, 1) """ if on_map: try: on_map = _on_map_test(traces[0]['x'][0], traces[0]['y'][0]) except: logger.warning( "Test if geo-data are in lat/long cannot be performed using geopy -> " "eventual plot errors are possible.") if on_map is False: logger.warning( "Existing geodata are not real lat/lon geographical coordinates. -> " "plot on maps is not possible.\n" "Use geo_data_to_latlong(net, projection) to transform geodata from specific projection." ) if on_map: # change traces for mapbox # change trace_type to scattermapbox and rename x to lat and y to lon for trace in traces: trace['lat'] = trace.pop('x') trace['lon'] = trace.pop('y') trace['type'] = 'scattermapbox' # setting Figure object fig = Figure( data=Data(traces), # edge_trace layout=Layout( titlefont=dict(size=16), showlegend=showlegend, autosize=True if aspectratio is 'auto' else False, hovermode='closest', margin=dict(b=5, l=5, r=5, t=5), # annotations=[dict( # text="", # showarrow=False, # xref="paper", yref="paper", # x=0.005, y=-0.002)], xaxis=XAxis(showgrid=False, zeroline=False, showticklabels=False), yaxis=YAxis(showgrid=False, zeroline=False, showticklabels=False), # legend=dict(x=0, y=1.0) ), ) # check if geodata are real geographycal lat/lon coordinates using geopy if on_map: try: mapbox_access_token = _get_mapbox_token() except Exception: logger.exception( 'mapbox token required for map plots. ' 'Get Mapbox token by signing in to https://www.mapbox.com/.\n' 'After getting a token, set it to pandapower using:\n' 'pandapower.plotting.plotly.mapbox_plot.set_mapbox_token(\'<token>\')' ) raise MapboxTokenMissing fig['layout']['mapbox'] = dict( accesstoken=mapbox_access_token, bearing=0, center=dict(lat=pd.Series(traces[0]['lat']).dropna().mean(), lon=pd.Series(traces[0]['lon']).dropna().mean()), style=map_style, pitch=0, zoom=11) # default aspectratio: if on_map use auto, else use 'original' aspectratio = 'original' if not on_map and aspectratio is 'auto' else aspectratio if aspectratio is not 'auto': if aspectratio is 'original': # TODO improve this workaround for getting original aspectratio xs = [] ys = [] for trace in traces: xs += trace['x'] ys += trace['y'] x_dropna = pd.Series(xs).dropna() y_dropna = pd.Series(ys).dropna() xrange = x_dropna.max() - x_dropna.min() yrange = y_dropna.max() - y_dropna.min() ratio = xrange / yrange if ratio < 1: aspectratio = (ratio, 1.) else: aspectratio = (1., 1 / ratio) aspectratio = np.array(aspectratio) / max(aspectratio) fig['layout']['width'], fig['layout']['height'] = ([ ar * figsize * 700 for ar in aspectratio ]) # check if called from ipynb or not in order to consider appropriate plot function if _in_ipynb(): from plotly.offline import init_notebook_mode, iplot as plot init_notebook_mode() else: from plotly.offline import plot as plot plot(fig)
def visualize_graph_clusters(graph: a3_part1.Graph, clusters: list[set], layout: str = 'spring_layout', max_vertices: int = 5000, output_file: str = '') -> None: """Visualize the given graph, using different colours to illustrate the different clusters. Hides all edges that go from one cluster to another. (This helps the graph layout algorithm positions vertices in the same cluster close together.) Same optional arguments as visualize_graph (see that function for details). """ graph_nx = graph.to_networkx(max_vertices) all_edges = list(graph_nx.edges) for edge in all_edges: # Check if edge is within the same cluster if any((edge[0] in cluster) != (edge[1] in cluster) for cluster in clusters): graph_nx.remove_edge(edge[0], edge[1]) pos = getattr(nx, layout)(graph_nx) x_values = [pos[k][0] for k in graph_nx.nodes] y_values = [pos[k][1] for k in graph_nx.nodes] labels = list(graph_nx.nodes) colors = [] for k in graph_nx.nodes: for i, c in enumerate(clusters): if k in c: colors.append(COLOUR_SCHEME[i % len(COLOUR_SCHEME)]) break else: colors.append(BOOK_COLOUR) x_edges = [] y_edges = [] for edge in graph_nx.edges: x_edges += [pos[edge[0]][0], pos[edge[1]][0], None] y_edges += [pos[edge[0]][1], pos[edge[1]][1], None] trace3 = Scatter(x=x_edges, y=y_edges, mode='lines', name='edges', line=dict(color=LINE_COLOUR, width=1), hoverinfo='none') trace4 = Scatter(x=x_values, y=y_values, mode='markers', name='nodes', marker=dict(symbol='circle-dot', size=5, color=colors, line=dict(color=VERTEX_BORDER_COLOUR, width=0.5)), text=labels, hovertemplate='%{text}', hoverlabel={'namelength': 0}) data1 = [trace3, trace4] fig = Figure(data=data1) fig.update_layout({'showlegend': False}) fig.update_xaxes(showgrid=False, zeroline=False, visible=False) fig.update_yaxes(showgrid=False, zeroline=False, visible=False) fig.show() if output_file == '': fig.show() else: fig.write_image(output_file)
username = '******' api_key = 'cC6LIzUltGaMR953sVxH' stream_token = 'a7adx0bmhu' stream_token_2 = 'e9w7o9hj9a' stream_token_3 = 'd5izfqfdn7' py.sign_in(username, api_key) trace1 = Scatter(x=[], y=[], stream=dict(token=stream_token, maxpoints=200)) trace2 = Scatter(x=[], y=[], stream=dict(token=stream_token_2, maxpoints=200)) trace3 = Scatter(x=[], y=[], stream=dict(token=stream_token_3, maxpoints=200)) layout = Layout(title='Acc 1 and 2') fig = Figure(data=[trace1, trace2], layout=layout) print py.plot(fig, filename='Raspberry Pi Streaming Example Values') stream = py.Stream(stream_token) stream.open() stream_2 = py.Stream(stream_token_2) stream_2.open() #stream_3 = py.Stream(stream_token_3) #stream_3.open() bus = smbus.SMBus(1) BMI160_DEVICE_ADDRESS = 0x69 BMI160_DEVICE_ADDRESS_2 = 0x68
def PlotShape(GRS, GRS2, ID1, ID2, savepic=False, shift=True, mode=3): if savepic: wline=5 pheight = 2000 pwidth = 4000 nwidth=5 else: wline=3 pheight = 500 pwidth = 1000 nwidth=2 edge_trace1 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='grey', width=wline), ) edge_trace2 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='blue', width=wline), ) if shift: ss=GRS.span/2 else: ss=0 for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = 0 y0 = 0 x1 = 0 y1 = 0 z0 = 0 z1 = 0 if mode in {0,1,3}: y0 = GRS.nsAll.y[sID] - ss y1 = GRS.nsAll.y[eID] - ss if mode in {0, 2, 3}: x0 = GRS.nsAll.x[sID] - ss x1 = GRS.nsAll.x[eID] - ss if mode in {0, 1, 2}: z0 = GRS.nsAll.z[sID] z1 = GRS.nsAll.z[eID] edge_trace1['x'] += [x0, x1, None] edge_trace1['y'] += [y0, y1, None] edge_trace1['z'] += [z0, z1, None] for i in range(GRS2.nbElAll): sID = GRS2.lsAll.sID[i] eID = GRS2.lsAll.eID[i] x0 = 0 y0 = 0 x1 = 0 y1 = 0 z0 = 0 z1 = 0 if mode in {0, 1, 3}: y0 = GRS2.nsAll.y[sID] y1 = GRS2.nsAll.y[eID] if mode in {0, 2, 3}: x0 = GRS2.nsAll.x[sID] x1 = GRS2.nsAll.x[eID] if mode in {0, 1, 2}: z0 = GRS2.nsAll.z[sID] z1 = GRS2.nsAll.z[eID] edge_trace2['x'] += [x0, x1, None] edge_trace2['y'] += [y0, y1, None] edge_trace2['z'] += [z0, z1, None] node_trace1 = Scatter3d( x=[], y=[], z=[], text=[], mode='markers', hoverinfo='text', marker=Marker( color=['red'], size=10, ), line=dict(width=nwidth)) if mode not in {1, 2, 3}: node_trace1['x'].append(GRS.nsAll.x[ID1]-ss) node_trace1['y'].append(GRS.nsAll.y[ID1]-ss) node_trace1['z'].append(GRS.nsAll.z[ID1]) node_trace2 = Scatter3d( x=[], y=[], z=[], text=[], mode='markers', hoverinfo='text', marker=Marker( color=['green'], size=10, ), line=dict(width=nwidth)) if mode not in {1,2,3}: node_trace2['x'].append(GRS2.nsAll.x[ID2]) node_trace2['y'].append(GRS2.nsAll.y[ID2]) node_trace2['z'].append(GRS2.nsAll.z[ID2]) if mode==1: camx=1 camy=0 camz=0 elif mode==2: camx=0 camy=1 camz=0 elif mode==3: camx=0 camy=0 camz=1 else: camx=-5 camy=-5 camz=5 scene = dict(camera=dict(eye=dict(x=camx, y=camy, z=camz)), aspectmode='data', xaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), yaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), zaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), ) fig = Figure(data=Data([edge_trace1, edge_trace2, node_trace1, node_trace2]), layout=Layout( showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), height=pheight, width=pwidth, scene=scene, )) return fig
def PlotNF(GRS, NForce, minid, maxid, scale): Nstart = -NForce[:, 0] Nend = NForce[:, 6] scale = scale * 1 / np.max(np.abs(np.append(Nstart, Nend))) edge_trace1 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='black'), ) edge_trace2 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='grey'), ) edge_trace3 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='red'), ) edge_trace4 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='blue'), ) for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = GRS.nsAll.x[sID] y0 = GRS.nsAll.y[sID] z0 = GRS.nsAll.z[sID] x1 = GRS.nsAll.x[eID] y1 = GRS.nsAll.y[eID] z1 = GRS.nsAll.z[eID] edge_trace1['x'] += [x0, x1, None] edge_trace1['y'] += [y0, y1, None] edge_trace1['z'] += [z0, z1, None] z0 += scale * Nstart[i] z1 += scale * Nend[i] if i == maxid: edge_trace3['x'] += [x0, x1, None] edge_trace3['y'] += [y0, y1, None] edge_trace3['z'] += [z0, z1, None] elif i == minid: edge_trace4['x'] += [x0, x1, None] edge_trace4['y'] += [y0, y1, None] edge_trace4['z'] += [z0, z1, None] else: edge_trace2['x'] += [x0, x1, None] edge_trace2['y'] += [y0, y1, None] edge_trace2['z'] += [z0, z1, None] for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = GRS.nsAll.x[sID] y0 = GRS.nsAll.y[sID] z0 = GRS.nsAll.z[sID] x1 = GRS.nsAll.x[eID] y1 = GRS.nsAll.y[eID] z1 = GRS.nsAll.z[eID] z0i = z0 + scale * Nstart[i] z1i = z1 + scale * Nend[i] if i == maxid: edge_trace3['x'] += [x0, x0, None] edge_trace3['y'] += [y0, y0, None] edge_trace3['z'] += [z0, z0i, None] edge_trace3['x'] += [x1, x1, None] edge_trace3['y'] += [y1, y1, None] edge_trace3['z'] += [z1, z1i, None] elif i == minid: edge_trace4['x'] += [x0, x0, None] edge_trace4['y'] += [y0, y0, None] edge_trace4['z'] += [z0, z0i, None] edge_trace4['x'] += [x1, x1, None] edge_trace4['y'] += [y1, y1, None] edge_trace4['z'] += [z1, z1i, None] else: edge_trace2['x'] += [x0, x0, None] edge_trace2['y'] += [y0, y0, None] edge_trace2['z'] += [z0, z0i, None] edge_trace2['x'] += [x1, x1, None] edge_trace2['y'] += [y1, y1, None] edge_trace2['z'] += [z1, z1i, None] fig = Figure(data=Data([edge_trace1, edge_trace2, edge_trace3, edge_trace4]), layout=Layout( showlegend=False, hovermode='closest', # margin=dict(b=20, l=5, r=5, t=40), height=500, width=1000, scene=dict( aspectmode='data', xaxis=dict( showgrid=False, zeroline=False), yaxis=dict( showgrid=False, zeroline=False), zaxis=dict( showgrid=False, zeroline=False), ), )) return fig
def __init__(self, doinit): #get my streams from config file self.pystream_ids = tls.get_credentials_file()['stream_ids'] #print self.pystream_ids stream_token_tboil = self.pystream_ids[0] stream_token_tnez = self.pystream_ids[1] stream_token_t4 = self.pystream_ids[2] stream_token_h4 = self.pystream_ids[3] stream_token_b9 = self.pystream_ids[4] stream_token_btarg = self.pystream_ids[5] stream_token_poids2 = self.pystream_ids[6] stream_token_fl = self.pystream_ids[7] #test date pyi = datetime.now().strftime("%Y-%m-%d %H:%M:%S") #backup poids self.oldPoids = 0 #layout trace1 = go.Scatter( x=[], y=[], name='T chaudiere', stream=dict(token=stream_token_tboil, maxpoints=2000), yaxis='y4', ) trace2 = go.Scatter(x=[], y=[], name='T extraction', stream=dict(token=stream_token_tnez, maxpoints=2000), line=dict(shape='spline')) trace3 = go.Scatter(x=[], y=[], name='T cuisine', stream=dict(token=stream_token_t4, maxpoints=2000), yaxis='y4') trace4 = go.Scatter( x=[], y=[], name='Hygro cuisine', stream=dict(token=stream_token_h4, maxpoints=2000), #opacity=0.4, yaxis='y5') trace5 = go.Scatter(x=[], y=[], name='Pression extraction', stream=dict(token=stream_token_b9, maxpoints=2000), yaxis='y2', line=dict(shape='spline')) trace6 = go.Scatter(x=[], y=[], name='Pression consigne', stream=dict(token=stream_token_btarg, maxpoints=2000), yaxis='y2') trace7 = go.Bar(x=[], y=[], name='Poids shot', stream=dict(token=stream_token_poids2, maxpoints=2000), opacity=0.4, yaxis='y3') trace8 = go.Scatter(x=[], y=[], name='Flow', stream=dict(token=stream_token_fl, maxpoints=2000), line=dict(simplify=False), yaxis='y6') trace9 = go.Scatter(x=[], y=[], name='OutFlow', stream=dict(token=self.pystream_ids[8], maxpoints=2000), line=dict(simplify=False), yaxis='y3') layout = go.Layout( title='My coffee shots', yaxis=dict(title='*C', domain=[0.55, 1], tickmode='linear', ticks='outside', tick0=0, dtick=1, range=[90, 95], rangemode='nonnegative'), yaxis2=dict(title='bar', titlefont=dict(color='rgb(148, 103, 189)'), tickfont=dict(color='rgb(148, 103, 189)'), overlaying='y', side='right', domain=[0.55, 1], rangemode='nonnegative'), yaxis3=dict(title='grams', domain=[0.2, 0.5], range=[0, 25], rangemode='nonnegative'), yaxis4=dict(title='*C', domain=[0, 0.2], rangemode='nonnegative'), yaxis5=dict(title='%hygro', side='right', overlaying='y4', layer="below traces", domain=[0, 0.2], rangemode='nonnegative'), yaxis6=dict( title='flow', side='right', overlaying='y3', rangemode='nonnegative', range=[0, 14], # layer="below traces", # domain=[0,0.2] ), ) #create figure object fig = Figure(data=[ trace1, trace2, trace3, trace4, trace5, trace6, trace7, trace8, trace9 ], layout=layout) #opening streams try: if (doinit): print "Init Plotly figure and layout..." print(py.plot(fig, filename='Mes shots plotly')) print "Opening Plotly streams..." self.stream_tboil = py.Stream(stream_token_tboil) self.stream_tboil.open() self.stream_tnez = py.Stream(stream_token_tnez) self.stream_tnez.open() self.stream_t4 = py.Stream(stream_token_t4) self.stream_t4.open() self.stream_h4 = py.Stream(stream_token_h4) self.stream_h4.open() self.stream_b9 = py.Stream(stream_token_b9) self.stream_b9.open() self.stream_btarg = py.Stream(stream_token_btarg) self.stream_btarg.open() self.stream_poids2 = py.Stream(stream_token_poids2) self.stream_poids2.open() self.stream_fl = py.Stream(stream_token_fl) self.stream_fl.open() self.stream_ofl = py.Stream(self.pystream_ids[8]) self.stream_ofl.open() self.mstreams = [ self.stream_tboil, self.stream_tnez, self.stream_t4, self.stream_h4, self.stream_b9, self.stream_btarg, self.stream_poids2, self.stream_fl, self.stream_ofl ] print "Plotly streams openned with success!" except Exception as e: print "Plotly STREAMS unexpected error:", sys.exc_info( )[0], " e=", repr(e)
def plot(self, value="value", fontSize=12, start=None, end=None, xLabel=None, yLabel=None, width=WIDTH, height=HEIGHT, withLabels=False, withWindows=False, withProbation=False, plotPath=None): """Plot the data stream.""" if value == "value": if yLabel is None: yLabel = "Metric" elif value == "raw": value = "raw_score" if yLabel is None: yLabel = "Prediction Error" elif value == "likelihood": value = "anomaly_score" if yLabel is None: yLabel = "Anomaly Likelihood" else: raise ValueError("Unknown value type '%s'".format(value)) detector = "numenta" dataDir, dataFile = os.path.split(self.dataPath) dataDir = os.path.split(dataDir)[1] resultsFile = detector + "_" + dataFile resultsPath = os.path.join(os.path.dirname(__file__), os.path.pardir, "results", detector, dataDir, resultsFile) resultsData = getCSVData(resultsPath) traces = [] traces.append(self._addScores(resultsData, value, yLabel, start, end)) if withLabels: labels = getJSONData( os.path.join(self.labelsDir, "combined_labels.json"))[self.dataFile] traces.append( self._addLabels(resultsData, labels, target=value, start=start, end=end)) if withWindows: traces.append(self._addWindows(start=start, end=end)) if withProbation: traces.append(self._addProbation(start=start, end=end)) # Create plotly Data and Layout objects: data = Data(traces) layout = self._createLayout(self.dataName, xLabel=xLabel, yLabel=yLabel, fontSize=fontSize, width=width, height=height) # Query plotly fig = Figure(data=data, layout=layout) if plotPath is None: # We temporarily switch to a temp directory to avoid overwriting the # previous plot when in offline mode. cwd = os.getcwd() tempBase = os.path.join(cwd, "plot_") tempDir = tempfile.mkdtemp(prefix=tempBase) try: os.chdir(tempDir) plotPath = self.py.plot(fig) print "Data plot URL: ", plotPath finally: os.chdir(cwd) else: self.py.image.save_as(fig, plotPath, width=width, height=height, scale=SCALE) return plotPath
y=[], mode='lines+markers', stream=Stream(token=stream_ids[5], maxpoints=80), name="Median Turbidity (NTU)") # Set up data sets plot_data = Data( [turbidity, turbidity2, turbidity3, temperature, depth, median]) # Configure the Layout layout = Layout(title='NTU Over Time', xaxis=XAxis(title='Date Time'), yaxis=YAxis(title='Turbidity(NTU)')) # Create the plot itself fig = Figure(data=plot_data, layout=layout) # Generate plot.ly URL based on name unique_url = py.plot(fig, filename='WATRDataStream_With_Median') # Holds the connections to the streams stream_link = py.Stream(stream_id) fftnMinTurb_link = py.Stream(stream_ids[1]) dailyTurb_link = py.Stream(stream_ids[2]) liveTurb_link = py.Stream(stream_ids[3]) fftnDepth_link = py.Stream(stream_ids[4]) fftnTemp_link = py.Stream(stream_ids[5]) # Holds whether update_plot is currently running collecting = False def update_plot(table):
def test_append_trace_before_make_subplots(): trace = Scatter(x=[1, 2, 3], y=[2, 3, 4]) fig = Figure() fig.append_trace(trace, 2, 2)
Scatter( x=[20, 30, 40], y=[50, 60, 70], xaxis='x2', yaxis='y2' ) ] layout = Layout( xaxis=dict( domain=[0, 0.7] ), xaxis2=dict( domain=[0.8, 1] ), yaxis2=dict( anchor='x2' ) ) figure = Figure(data=data, layout=layout) plot(figure, filename='../output/plotly_side_by_side.html', auto_open=False) logger.info('done') finish_time = time() elapsed_hours, elapsed_remainder = divmod(finish_time - start_time, 3600) elapsed_minutes, elapsed_seconds = divmod(elapsed_remainder, 60) logger.info('Time: {:0>2}:{:0>2}:{:05.2f}'.format(int(elapsed_hours), int(elapsed_minutes), elapsed_seconds)) console_handler.close() logger.removeHandler(console_handler)
def plotMultipleDetectors(self, resultsPaths, detectors=["numenta"], scoreProfile="standard", withLabels=True, withWindows=True, withProbation=True): """ Plot detector results on a data file. TODO: auto-generate paths from dataFile and detectors. """ if scoreProfile is (not "standard" or not "reward_low_fn_rate" or not "reward_low_fp_rate"): raise ValueError( "Invalid scoring profile. Must be one of \'standard\' " "or \'reward low fn rate\' or \'reward low fp rate\'.") if self.rawData is None: self.rawData = getCSVData(self.dataPath) traces = [] traces.append(self._addValues(self.rawData)) # Anomaly detections traces: for i, d in enumerate(detectors): threshold = self.thresholds[d][scoreProfile]["threshold"] resultsData = getCSVData( os.path.join(self.resultsDir, resultsPaths[i])) FP, TP = self._parseDetections(resultsData, threshold) fpTrace, tpTrace = self._addDetections("Detection by " + d, MARKERS[i + 1], FP, TP) traces.append(fpTrace) traces.append(tpTrace) if withLabels: labels = getJSONData( os.path.join(self.labelsDir, "combined_labels.json"))[self.dataFile] traces.append(self._addLabels(self.rawData, labels, target="value")) if withWindows: traces.append(self._addWindows()) if withProbation: traces.append(self._addProbation()) # Create plotly Data and Layout objects: data = Data(traces) layout = self._createLayout("Anomaly Detections for " + self.dataName) # Query plotly fig = Figure(data=data, layout=layout) plot_url = self.py.plot(fig) print "Detections plot URL: ", plot_url return plot_url
def PlotMom(GRS, MForce, scale): Mstart = -MForce[:, 4] Mend = MForce[:, 10] scale = scale * 1 / np.max(np.abs(np.append(Mstart, Mend))) edge_trace1 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='grey'), ) edge_trace2 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='blue'), ) for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = GRS.nsAll.x[sID] y0 = GRS.nsAll.y[sID] z0 = GRS.nsAll.z[sID] x1 = GRS.nsAll.x[eID] y1 = GRS.nsAll.y[eID] z1 = GRS.nsAll.z[eID] edge_trace1['x'] += [x0, x1, None] edge_trace1['y'] += [y0, y1, None] edge_trace1['z'] += [z0, z1, None] z0 += scale * Mstart[i] z1 += scale * Mend[i] edge_trace2['x'] += [x0, x1, None] edge_trace2['y'] += [y0, y1, None] edge_trace2['z'] += [z0, z1, None] for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = GRS.nsAll.x[sID] y0 = GRS.nsAll.y[sID] z0 = GRS.nsAll.z[sID] x1 = GRS.nsAll.x[eID] y1 = GRS.nsAll.y[eID] z1 = GRS.nsAll.z[eID] z0i = z0 + scale * Mstart[i] z1i = z1 + scale * Mend[i] edge_trace1['x'] += [x0, x0, None] edge_trace1['y'] += [y0, y0, None] edge_trace1['z'] += [z0, z0i, None] edge_trace2['x'] += [x1, x1, None] edge_trace2['y'] += [y1, y1, None] edge_trace2['z'] += [z1, z1i, None] fig = Figure(data=Data([edge_trace1, edge_trace2]), layout=Layout( showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), height=1000, width=2000, scene=dict( aspectmode='data', xaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), yaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), zaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), ), )) return fig
def treemap_military_spending_2015(): def format_spending_text(tup): return str(tup[0] + '<br>${:,.2f}B.'.format(tup[1] / 1000)) #Colors taken from colorbrewer2.org colors = [ 'rgb(165,0,38)', 'rgb(215,48,39)', 'rgb(244,109,67)', 'rgb(253,174,97)', 'rgb(254,224,144)', 'rgb(255,255,191)', 'rgb(224,243,248)', 'rgb(171,217,233)', 'rgb(116,173,209)', 'rgb(69,117,180)', 'rgb(49,54,149)' ] #Read in data data = [] with open('data/SIPRI-Milex-data-1988-2015-cleaned-current-usd.csv' ) as current_usd: reader = csv.reader(current_usd) headers = next(reader, None)[1:] for row in reader: #Data unavailable, or country didn't exist at the time if ('. .' in row[12:] or 'xxx' in row[12:]): continue data.append((row[0], float(row[-1]))) #Sort data by amount spent in 2015, select top 15 spenders data = sorted(data, key=lambda tup: tup[1])[len(data) - 15:] #Squarify data x = 0 y = 0 width = 100 height = 100 normed = squarify.normalize_sizes([tup[1] for tup in data], width, height) rects = squarify.squarify(normed, x, y, width, height) #Generate treemap (taken directly from https://plot.ly/python/treemaps/) shapes = [] annotations = [] color_counter = 5 country_counter = 0 for r in rects: shapes.append( dict(type='rect', x0=r['x'], y0=r['y'], x1=r['x'] + r['dx'], y1=r['y'] + r['dy'], line=dict(width=2), fillcolor=colors[color_counter])) annotations.append( dict(x=r['x'] + (r['dx'] / 2), y=r['y'] + (r['dy'] / 2), text=format_spending_text(data[country_counter]), font=dict(family='Courier New, monospace', size=15, color='#000000'), showarrow=False)) color_counter += 1 country_counter += 1 if color_counter >= len(colors): color_counter = 0 # For hover text trace = Scatter( x=[r['x'] + (r['dx'] / 2) for r in rects], y=[r['y'] + (r['dy'] / 2) for r in rects], text=['${:,.2f}'.format(tup[1] * 1000) for tup in data], mode='text', ) layout = dict(height=900, width=900, shapes=shapes, annotations=annotations, hovermode='closest', title='Top 15 National Expenditures on Military 2015', font=dict(family='Courier New, monospace', size=21, color='#000000')) #Plot treemap fig = Figure(data=[trace], layout=layout) plot(fig, filename="images/military-spending-2015-treemap")
def test_print_grid_before_make_subplots(): fig = Figure() fig.print_grid()
def PlotImp(GRS,GRSimp, scale, savepic=False): if savepic: wline=5 pheight = 2000 pwidth = 4000 else: wline=3 pheight = 500 pwidth = 1000 edge_trace = Scatter3d( x=[], y=[], z=[], # hoverinfo='none', line=dict(color='grey',width=wline), mode='lines') edge_trace2 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='blue', width=wline), ) for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = GRS.nsAll.x[sID] y0 = GRS.nsAll.y[sID] z0 = GRS.nsAll.z[sID] x1 = GRS.nsAll.x[eID] y1 = GRS.nsAll.y[eID] z1 = GRS.nsAll.z[eID] edge_trace['x'] += [x0, x1, None] edge_trace['y'] += [y0, y1, None] edge_trace['z'] += [z0, z1, None] sID = GRSimp.lsAll.sID[i] eID = GRSimp.lsAll.eID[i] x0 = GRS.nsAll.x[sID] + (GRSimp.nsAll.x[sID]-GRS.nsAll.x[sID])*scale y0 = GRS.nsAll.y[sID] + (GRSimp.nsAll.y[sID]-GRS.nsAll.y[sID])*scale z0 = GRS.nsAll.z[sID] + (GRSimp.nsAll.z[sID]-GRS.nsAll.z[sID])*scale x1 = GRS.nsAll.x[eID] + (GRSimp.nsAll.x[eID]-GRS.nsAll.x[eID])*scale y1 = GRS.nsAll.y[eID] + (GRSimp.nsAll.y[eID]-GRS.nsAll.y[eID])*scale z1 = GRS.nsAll.z[eID] + (GRSimp.nsAll.z[eID]-GRS.nsAll.z[eID])*scale edge_trace2['x'] += [x0, x1, None] edge_trace2['y'] += [y0, y1, None] edge_trace2['z'] += [z0, z1, None] fig = Figure(data=Data([edge_trace,edge_trace2]), layout=Layout( showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), height=pheight, width=pwidth, scene=dict( aspectmode='data', xaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False), yaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False), zaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False), ), )) return fig
class TestGetData(TestCase): fig = None def setUp(self): super(TestGetData, self).setUp() self.fig = Figure( data=Data([ Scatter( x=[52698, 43117], y=[53, 31], mode='markers', name='North America', text=['United States', 'Canada'], marker=Marker( color='rgb(164, 194, 244)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[39317, 37236, 35650, 30066, 29570, 27159, 23557, 21046, 18007], y=[33, 20, 13, 19, 27, 19, 49, 44, 38], mode='markers', name='Europe', text=['Germany', 'Britain', 'France', 'Spain', 'Italy', 'Czech Rep.', 'Greece', 'Poland'], marker=Marker( color='rgb(255, 217, 102)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[42952, 37037, 33106, 17478, 9813, 5253, 4692, 3899], y=[23, 42, 54, 89, 14, 99, 93, 70], mode='markers', name='Asia/Pacific', text=['Australia', 'Japan', 'South Korea', 'Malaysia', 'China', 'Indonesia', 'Philippines', 'India'], marker=Marker( color='rgb(234, 153, 153)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[19097, 18601, 15595, 13546, 12026, 7434, 5419], y=[43, 47, 56, 80, 86, 93, 80], mode='markers', name='Latin America', text=['Chile', 'Argentina', 'Mexico', 'Venezuela', 'Venezuela', 'El Salvador', 'Bolivia'], marker=Marker( color='rgb(142, 124, 195)', size=12, line=Line( color='white', width=0.5 ) ) ) ]), layout=Layout( title='Quarter 1 Growth', autosize=False, width=500, height=500, xaxis=XAxis( title='GDP per Capita', showgrid=False, zeroline=False ), yaxis=YAxis( title='Percent', showline=False ), margin=Margin( l=65, r=50, b=65, t=90 ) ) ) def test_get_data(self): data = self.fig.get_data() comp_data = [ { 'name': 'North America', 'text': ['United States', 'Canada'], 'x': [52698, 43117], 'y': [53, 31] }, { 'name': 'Europe', 'text': ['Germany', 'Britain', 'France', 'Spain', 'Italy', 'Czech Rep.', 'Greece', 'Poland'], 'x': [39317, 37236, 35650, 30066, 29570, 27159, 23557, 21046, 18007], 'y': [33, 20, 13, 19, 27, 19, 49, 44, 38] }, { 'name': 'Asia/Pacific', 'text': ['Australia', 'Japan', 'South Korea', 'Malaysia', 'China', 'Indonesia', 'Philippines', 'India'], 'x': [42952, 37037, 33106, 17478, 9813, 5253, 4692, 3899], 'y': [23, 42, 54, 89, 14, 99, 93, 70]}, { 'name': 'Latin America', 'text': ['Chile', 'Argentina', 'Mexico', 'Venezuela', 'Venezuela', 'El Salvador', 'Bolivia'], 'x': [19097, 18601, 15595, 13546, 12026, 7434, 5419], 'y': [43, 47, 56, 80, 86, 93, 80] } ] self.assertEqual(data, comp_data) def test_get_data_flatten(self): # this is similar to above, except nested objects are flattened flat_data = self.fig.get_data(flatten=True) comp_data = { 'Europe.x': [39317, 37236, 35650, 30066, 29570, 27159, 23557, 21046, 18007], 'Europe.y': [33, 20, 13, 19, 27, 19, 49, 44, 38], 'Asia/Pacific.x': [42952, 37037, 33106, 17478, 9813, 5253, 4692, 3899], 'Latin America.text': ['Chile', 'Argentina', 'Mexico', 'Venezuela', 'Venezuela', 'El Salvador', 'Bolivia'], 'North America.x': [52698, 43117], 'Asia/Pacific.y': [23, 42, 54, 89, 14, 99, 93, 70], 'Asia/Pacific.text': ['Australia', 'Japan', 'South Korea', 'Malaysia', 'China', 'Indonesia', 'Philippines', 'India'], 'North America.y': [53, 31], 'North America.text': ['United States', 'Canada'], 'Europe.text': ['Germany', 'Britain', 'France', 'Spain', 'Italy', 'Czech Rep.', 'Greece', 'Poland'], 'Latin America.x': [19097, 18601, 15595, 13546, 12026, 7434, 5419], 'Latin America.y': [43, 47, 56, 80, 86, 93, 80] } self.assertEqual(flat_data, comp_data) # TODO test for Data, Scatter, etc.. def test_flatten_repeated_trace_names(self): dl = Data([Scatter(name='thesame', x=[1, 2, 3]) for _ in range(3)]) data = dl.get_data(flatten=True) comp_data = { 'thesame.x': [1, 2, 3], 'thesame_1.x': [1, 2, 3], 'thesame_2.x': [1, 2, 3] } self.assertEqual(data, comp_data)
def PlotDef(GRS, ID, NDisp, scale, small=False, deflOnly=False, mode=0): edge_trace1 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='grey'), ) edge_trace2 = Scatter3d( x=[], y=[], z=[], mode='lines', line=dict(color='blue'), ) for i in range(GRS.nbElAll): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = 0 y0 = 0 x1 = 0 y1 = 0 z0 = 0 z1 = 0 if mode in {0, 2, 3}: x0 = GRS.nsAll.x[sID] x1 = GRS.nsAll.x[eID] if mode in {0, 1, 3}: y0 = GRS.nsAll.y[sID] y1 = GRS.nsAll.y[eID] if mode in {0, 1, 2}: z0 = GRS.nsAll.z[sID] z1 = GRS.nsAll.z[eID] edge_trace1['x'] += [x0, x1, None] edge_trace1['y'] += [y0, y1, None] edge_trace1['z'] += [z0, z1, None] if mode in {0, 2, 3}: x0 -= scale * NDisp[sID, 0] * un.mm x1 -= scale * NDisp[eID, 0] * un.mm if mode in {0, 1, 3}: y0 -= scale * NDisp[sID, 1] * un.mm y1 -= scale * NDisp[eID, 1] * un.mm if mode in {0, 1, 2}: z1 -= scale * NDisp[eID, 2] * un.mm z0 -= scale * NDisp[sID, 2] * un.mm edge_trace2['x'] += [x0, x1, None] edge_trace2['y'] += [y0, y1, None] edge_trace2['z'] += [z0, z1, None] if not small: for i in range(GRS.nbElAll-1): sID = GRS.lsAll.sID[i] eID = GRS.lsAll.eID[i] x0 = 0 y0 = 0 x1 = 0 y1 = 0 z0 = 0 z1 = 0 if mode in {0, 2, 3}: x0 = GRS.nsAll.x[sID] x1 = GRS.nsAll.x[eID] x0i = x0 - scale * NDisp[sID, 0] * un.mm x1i = x1 - scale * NDisp[eID, 0] * un.mm if mode in {0, 1, 3}: y0 = GRS.nsAll.y[sID] y1 = GRS.nsAll.y[eID] y0i = y0 - scale * NDisp[sID, 1] * un.mm y1i = y1 - scale * NDisp[eID, 1] * un.mm if mode in {0, 1, 2}: z0 = GRS.nsAll.z[sID] z1 = GRS.nsAll.z[eID] z0i = z0 - scale * NDisp[sID, 2] * un.mm z1i = z1 - scale * NDisp[eID, 2] * un.mm edge_trace1['x'] += [x0, x0i, None] edge_trace1['y'] += [y0, y0i, None] edge_trace1['z'] += [z0, z0i, None] edge_trace2['x'] += [x1, x1i, None] edge_trace2['y'] += [y1, y1i, None] edge_trace2['z'] += [z1, z1i, None] node_trace = Scatter3d( x=[], y=[], z=[], text=[], mode='markers', hoverinfo='text', marker=Marker( color=['red'], size=5, ), line=dict(width=2)) if mode==1: node_trace['x'].append(0) else: node_trace['x'].append(GRS.nsAll.x[ID]) if mode==2: node_trace['y'].append(0) else: node_trace['y'].append(GRS.nsAll.y[ID]) if mode==3: node_trace['z'].append(0) else: node_trace['z'].append(GRS.nsAll.z[ID]) v=[edge_trace1, edge_trace2, node_trace] if deflOnly: v=[edge_trace2, node_trace] if mode==1: camx=1 camy=0 camz=0 elif mode==2: camx=0 camy=1 camz=0 elif mode==3: camx=0 camy=0 camz=1 else: camx=-5 camy=-5 camz=5 fig = Figure(data=Data(v), layout=Layout( showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), height=1000, width=2000, scene=dict( camera=dict(eye=dict(x=camx, y=camy, z=camz)), aspectmode='data', xaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), yaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False), zaxis=dict( showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False), ), )) return fig
def test_get_ordered(): fig = Figure( data=Data([ Scatter( x=[52698, 43117], y=[53, 31], mode='markers', name='North America', text=['United States', 'Canada'], marker=Marker( color='rgb(164, 194, 244)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[39317, 37236, 35650, 30066, 29570, 27159, 23557, 21046, 18007], y=[33, 20, 13, 19, 27, 19, 49, 44, 38], mode='markers', name='Europe', text=['Germany', 'Britain', 'France', 'Spain', 'Italy', 'Czech Rep.', 'Greece', 'Poland'], marker=Marker( color='rgb(255, 217, 102)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[42952, 37037, 33106, 17478, 9813, 5253, 4692, 3899], y=[23, 42, 54, 89, 14, 99, 93, 70], mode='markers', name='Asia/Pacific', text=['Australia', 'Japan', 'South Korea', 'Malaysia', 'China', 'Indonesia', 'Philippines', 'India'], marker=Marker( color='rgb(234, 153, 153)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[19097, 18601, 15595, 13546, 12026, 7434, 5419], y=[43, 47, 56, 80, 86, 93, 80], mode='markers', name='Latin America', text=['Chile', 'Argentina', 'Mexico', 'Venezuela', 'Venezuela', 'El Salvador', 'Bolivia'], marker=Marker( color='rgb(142, 124, 195)', size=12, line=Line( color='white', width=0.5 ) ) ) ]), layout=Layout( title='Quarter 1 Growth', autosize=False, width=500, height=500, xaxis=XAxis( title='GDP per Capita', showgrid=False, zeroline=False ), yaxis=YAxis( title='Percent', showline=False ), margin=Margin( l=65, r=50, b=65, t=90 ) ) ) ordered_fig = fig.get_ordered() comp_fig = OrderedDict( [('data', [ OrderedDict([ ('x', [52698, 43117]), ('y', [53, 31]), ('mode', 'markers'), ('name', 'North America'), ('text', ['United States', 'Canada']), ('marker', OrderedDict([ ('color', 'rgb(164, 194, 244)'), ('size', 12), ('line', OrderedDict([ ('color', 'white'), ('width', 0.5)]))])), ('type', 'scatter')]), OrderedDict([ ('x', [39317, 37236, 35650, 30066, 29570, 27159, 23557, 21046, 18007]), ('y', [33, 20, 13, 19, 27, 19, 49, 44, 38]), ('mode', 'markers'), ('name', 'Europe'), ('text', ['Germany', 'Britain', 'France', 'Spain', 'Italy', 'Czech Rep.', 'Greece', 'Poland']), ('marker', OrderedDict([ ('color', 'rgb(255, 217, 102)'), ('size', 12), ('line', OrderedDict([ ('color', 'white'), ('width', 0.5)]))])), ('type', 'scatter')]), OrderedDict([ ('x', [42952, 37037, 33106, 17478, 9813, 5253, 4692, 3899]), ('y', [23, 42, 54, 89, 14, 99, 93, 70]), ('mode', 'markers'), ('name', 'Asia/Pacific'), ('text', ['Australia', 'Japan', 'South Korea', 'Malaysia', 'China', 'Indonesia', 'Philippines', 'India']), ('marker', OrderedDict([ ('color', 'rgb(234, 153, 153)'), ('size', 12), ('line', OrderedDict([ ('color', 'white'), ('width', 0.5)]))])), ('type', 'scatter')]), OrderedDict([ ('x', [19097, 18601, 15595, 13546, 12026, 7434, 5419]), ('y', [43, 47, 56, 80, 86, 93, 80]), ('mode', 'markers'), ('name', 'Latin America'), ('text', ['Chile', 'Argentina', 'Mexico', 'Venezuela', 'Venezuela', 'El Salvador', 'Bolivia']), ('marker', OrderedDict([ ('color', 'rgb(142, 124, 195)'), ('size', 12), ('line', OrderedDict([ ('color', 'white'), ('width', 0.5)]))])), ('type', 'scatter')])]), ('layout', OrderedDict([ ('title', 'Quarter 1 Growth'), ('autosize', False), ('width', 500), ('height', 500), ('xaxis', OrderedDict([ ('title', 'GDP per Capita'), ('showgrid', False), ('zeroline', False)])), ('yaxis', OrderedDict([ ('title', 'Percent'), ('showline', False)])), ('margin', OrderedDict([ ('l', 65), ('r', 50), ('b', 65), ('t', 90)]))]))]) assert ordered_fig == comp_fig
def plotGamma(muG, muA, eps, pathout, title, doLog=False): x = np.linspace(0., 1., 50) y = np.linspace(0., 1., 50) X = np.tile(np.array([x]).transpose(), (1, len(x))) Y = np.tile(np.array(y), (len(y), 1)) Zpos = computeGammaPos(muG, muA, X, Y, eps) Zneg = computeGammaNeg(muG, muA, X, Y, eps) gammaTit = '$\\Gamma$' cdist = np.zeros(Zpos.shape) if doLog: Zpos = np.log(Zpos) Zneg = np.log(Zneg) gammaTit = '$\\log\\Gamma$' #trace1 = Surface() data = [ dict(x=X, y=Y, z=Zpos, opacity=0.9, showscale=False, surfacecolor=cdist, colorscale=[[0.0, 'rgb(0, 0, 180)'], [1.0, 'rgb(0, 0, 180)']], type='surface', name='Positive root'), dict(x=X, y=Y, z=Zneg, opacity=0.9, showscale=False, surfacecolor=cdist, colorscale=[[0.0, 'rgb(0, 180, 180)'], [1.0, 'rgb(0, 180, 180)']], type='surface', name='Negative root') ] data0 = [ dict(x=X, y=Y, z=Zpos, opacity=0.9, showscale=False, surfacecolor=cdist, colorscale=[[0.0, 'rgb(0, 0, 180)'], [1.0, 'rgb(0, 0, 180)']], type='surface', name='Positive root') ] data1 = [ dict(x=X, y=Y, z=Zneg, opacity=0.9, showscale=False, surfacecolor=cdist, colorscale=[[0.0, 'rgb(0, 180, 0)'], [1.0, 'rgb(0, 180, 0)']], type='surface', name='Negative root') ] fn = '%s/gamma_%s_eff%d' % (pathout, title, 100 * eps) layout = Layout(scene=dict( xaxis=dict(title='$\\psi$'), yaxis=dict(title='$\\phi$'), zaxis=dict(title=gammaTit), )) fig = Figure(data=data, layout=layout) plot(fig, filename=fn) return
class TestToDataframe(TestCase): fig = None def setUp(self): super(TestToDataframe, self).setUp() self.fig = Figure( data=Data([ Scatter( x=[52698, 43117], y=[53, 31], mode='markers', name='North America', text=['United States', 'Canada'], marker=Marker( color='rgb(164, 194, 244)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[39317, 37236, 35650, 30066, 29570, 27159, 23557, 21046, 18007], y=[33, 20, 13, 19, 27, 19, 49, 44, 38], mode='markers', name='Europe', text=['Germany', 'Britain', 'France', 'Spain', 'Italy', 'Czech Rep.', 'Greece', 'Poland'], marker=Marker( color='rgb(255, 217, 102)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[42952, 37037, 33106, 17478, 9813, 5253, 4692, 3899], y=[23, 42, 54, 89, 14, 99, 93, 70], mode='markers', name='Asia/Pacific', text=['Australia', 'Japan', 'South Korea', 'Malaysia', 'China', 'Indonesia', 'Philippines', 'India'], marker=Marker( color='rgb(234, 153, 153)', size=12, line=Line( color='white', width=0.5 ) ) ), Scatter( x=[19097, 18601, 15595, 13546, 12026, 7434, 5419], y=[43, 47, 56, 80, 86, 93, 80], mode='markers', name='Latin America', text=['Chile', 'Argentina', 'Mexico', 'Venezuela', 'Venezuela', 'El Salvador', 'Bolivia'], marker=Marker( color='rgb(142, 124, 195)', size=12, line=Line( color='white', width=0.5 ) ) ) ]), layout=Layout( title='Quarter 1 Growth', autosize=False, width=500, height=500, xaxis=XAxis( title='GDP per Capita', showgrid=False, zeroline=False ), yaxis=YAxis( title='Percent', showline=False ), margin=Margin( l=65, r=50, b=65, t=90 ) ) ) def test_figure_to_dataframe(self): df = self.fig.to_dataframe() self.assertEqual(len(df), 9) self.assertEqual(len(df.columns), 12)
ANNOTATIONS = Figure(data=Data([ Scatter(x=[0.0, 1.0, 2.0], y=[1.0, 2.0, 3.0], name='_line0', mode='lines', line=Line(dash='solid', color='#0000FF', width=1.0, opacity=1), xaxis='x1', yaxis='y1'), Scatter(x=[0.0, 1.0, 2.0], y=[3.0, 2.0, 1.0], name='_line1', mode='lines', line=Line(dash='solid', color='#0000FF', width=1.0, opacity=1), xaxis='x1', yaxis='y1') ]), layout=Layout(width=640, height=480, autosize=False, margin=Margin(l=80, r=63, b=47, t=47, pad=0), hovermode='closest', showlegend=False, annotations=Annotations([ Annotation(x=0.000997987927565, y=0.996414507772, text='top-left', xref='paper', yref='paper', showarrow=False, align='left', font=Font(size=12.0, color='#000000'), opacity=1, xanchor='left', yanchor='top'), Annotation(x=0.000997987927565, y=0.00358549222798, text='bottom-left', xref='paper', yref='paper', align='left', showarrow=False, font=Font(size=12.0, color='#000000'), opacity=1, xanchor='left', yanchor='bottom'), Annotation(x=0.996989939638, y=0.996414507772, text='top-right', xref='paper', yref='paper', align='right', showarrow=False, font=Font(size=12.0, color='#000000'), opacity=1, xanchor='right', yanchor='top'), Annotation(x=0.996989939638, y=0.00358549222798, text='bottom-right', xref='paper', yref='paper', align='right', showarrow=False, font=Font(size=12.0, color='#000000'), opacity=1, xanchor='right', yanchor='bottom') ]), xaxis1=XAxis(domain=[0.0, 1.0], range=(0.0, 2.0), showline=True, ticks='inside', showgrid=False, zeroline=False, anchor='y1', mirror=True), yaxis1=YAxis(domain=[0.0, 1.0], range=(1.0, 3.0), showline=True, ticks='inside', showgrid=False, zeroline=False, anchor='x1', mirror=True)))