def get_rpm_speed_graph(df: pd.DataFrame) -> dcc.Graph: rpm_data = Scatter(y=df['rpm'], name='RPM', mode='lines+markers') speed_data = Scatter(y=df['vss'], name='Speed', mode='lines+markers', yaxis='y2') graph_layout = dict(title='RPM and Speed', xaxis=dict(title='Time Elapsed (sec)', range=[0, 30], fixedrange=True, tickvals=[0, 10, 20, 30], ticktext=['30', '20', '10', '0']), yaxis=dict( title='{}'.format(PROPERTIES['rpm']), zeroline=False, ), yaxis2=dict( title='{}'.format(PROPERTIES['vss']), overlaying='y', side='right', zeroline=False, ), legend={ 'x': 0, 'y': 1 }, margin=Margin(t=45, l=50, r=50)) return dcc.Graph(id='rpm_speed', figure={ 'data': [rpm_data, speed_data], 'layout': graph_layout })
def get_generic_graph_over_time(df: pd.DataFrame, key: str) -> dcc.Graph: data = Scatter( y=df[key], fill='tozeroy', line=dict(color='#1E65F3', ), fillcolor='#9DC3E6', mode='lines+markers', ) graph_layout = dict(title='{}'.format(PROPERTIES[key]), xaxis=dict(title='Time Elapsed (sec)', range=[0, 30], showgrid=False, showline=True, zeroline=False, fixedrange=True, tickvals=[0, 10, 20, 30], ticktext=['30', '20', '10', '0']), yaxis=dict(title='{}'.format(PROPERTIES[key]), range=[min(df[key]), max(df[key])], zeroline=False, fixedrange=False), margin=Margin(t=45, l=50, r=50)) return dcc.Graph(id=key, figure={'data': [data], 'layout': graph_layout})
def set_margins(l=60, r=60, b=40, t=0, pad=5): return Margin( l=l, r=r, b=b, t=t, pad=pad )
def update_graph_user(user): zoom = 12.0 latInitial = 37.766083 lonInitial = -122.448649 bearing = 0 venue_list = session.execute("select venue_id, user_id, lat, log, rating from friendratingloc WHERE user_id = \'{}\'".format(user)) venue_name = [] venue_lat = [] venue_lon = [] venue_rating = [] for venue in venue_list: venue_name.append(venue.venue_id) venue_lat.append(venue.lat) venue_lon.append(venue.log) venue_rating.append(venue.rating) return go.Figure( data=[ Scattermapbox( #lat=["37.752443", "37.807771", "37.810088", "37.769361", "37.802067"], #lon=["-122.447543", "-122.473899", "-122.410428", "-122.485742", # "-122.418840"], lat = venue_lat, lon = venue_lon, mode='markers', hoverinfo="text", text = venue_rating, #text=["1", "2", "3", "4", "5"], # opacity=0.5, marker=dict( size=12, color=venue_rating ), ), ], layout=Layout( autosize=True, height=750, margin=Margin(l=0, r=0, t=0, b=0), showlegend=False, mapbox=dict( accesstoken=mapbox_access_token, center=dict( lat=latInitial, # 40.7272 lon=lonInitial # -73.991251 ), style='dark', bearing=bearing, zoom=zoom ) ) )
def update_histogram(value, slider_value, selection): [xVal, yVal, xSelected, colorVal] = get_selection(value, slider_value, selection) layout = go.Layout( bargap=0.01, bargroupgap=0, barmode='group', margin=Margin(l=10, r=0, t=0, b=30), showlegend=False, plot_bgcolor='#323130', paper_bgcolor='rgb(66, 134, 244, 0)', height=250, dragmode="select", xaxis=dict(range=[-0.5, 23.5], showgrid=False, nticks=25, fixedrange=True, ticksuffix=":00"), yaxis=dict(range=[0, max(yVal) + max(yVal) / 4], showticklabels=False, showgrid=False, fixedrange=True, rangemode='nonnegative', zeroline=False), annotations=[ dict( x=xi, y=yi, text=str(yi), xanchor='center', yanchor='bottom', showarrow=False, font=dict(color='white'), ) for xi, yi in zip(xVal, yVal) ], ) return go.Figure(data=Data([ go.Bar(x=xVal, y=yVal, marker=dict(color=colorVal), hoverinfo="x"), go.Scatter(opacity=0, x=xVal, y=yVal / 2, hoverinfo="none", mode='markers', marker=go.Marker(color='rgb(66, 134, 244, 0)', symbol="square", size=40), visible=True) ]), layout=layout)
def plotly_plot(df_in, x_column, plot_title=None, y_left_label=None, y_right_label=None, bar_plot=False, figsize=(16, 10), number_of_ticks_display=20, yaxis2_cols=None): ya2c = [] if yaxis2_cols is None else yaxis2_cols ycols = [c for c in df_in.columns.values if c != x_column] # create tdvals, which will have x axis labels td = list(df_in[x_column]) nt = len(df_in) - 1 if number_of_ticks_display > len( df_in) else number_of_ticks_display spacing = len(td) // nt tdvals = td[::spacing] # create data for graph data = [] # iterate through all ycols to append to data that gets passed to go.Figure for ycol in ycols: if bar_plot: b = go.Bar(x=td, y=df_in[ycol], name=ycol, yaxis='y' if ycol not in ya2c else 'y2') else: b = go.Scatter(x=td, y=df_in[ycol], name=ycol, yaxis='y' if ycol not in ya2c else 'y2') data.append(b) # create a layout layout = go.Layout( title=plot_title, xaxis=dict(ticktext=tdvals, tickvals=tdvals, tickangle=45, type='category'), yaxis=dict(title='y main' if y_left_label is None else y_left_label), yaxis2=dict(title='y alt' if y_right_label is None else y_right_label, overlaying='y', side='right'), margin=Margin(b=100)) fig = go.Figure(data=data, layout=layout) return fig
def update_graph(json_cached_readings): if json_cached_readings is None: return '' if json_cached_readings == ACCESS_REVOKED: return html.Div( 'Your access has either not been granted or has been revoked!', style={'color': 'red'}) cached_hb_values = json.loads(json_cached_readings, object_pairs_hook=collections.OrderedDict) if len(cached_hb_values) == 0: return '' df = pd.DataFrame({'HB': list(cached_hb_values.values())}) trace = Scatter( y=df['HB'], line=Line(color='#1E65F3'), mode='lines+markers', ) graph_layout = Layout(height=450, xaxis=dict(title='Time Elapsed (sec)', range=[0, 30], showgrid=False, showline=True, zeroline=False, fixedrange=True, tickvals=[0, 10, 20, 30], ticktext=['30', '20', '10', '0']), yaxis=dict(title='Heart Rate (bpm)', range=[50, 110], showline=True, fixedrange=True, zeroline=False, nticks=10), margin=Margin(t=45, l=50, r=50)) return dcc.Graph(id='hb_table', figure={ 'data': [trace], 'layout': graph_layout })
def plot_colored_table( master_values: np.ndarray, branch_values: np.ndarray, row_labels: List[str], col_labels: List[str], tab_data: np.ndarray, ) -> str: """Create an annotated heatmap of shape (H,W), where there are H metrics, and W benchmark datasets. Args: master_values: array of shape (H,W), representing values in master branch_values: array of shape (H,W), representing values in new branch col_labels: list of length (W), representing labels for each column (column names) in the "x" direction. row_labels: list of length (H), representing labels for each row (row names) in the "y" direction. tab_data: (H,W) 2d matrix, representing table data. Entries of the table represent percentage changes from a value for a metric on the master branch. Values can be considered in the "z" direction. Returns: string representing HTML code for the generated Plotly table. """ if tab_data.size == 0: return "" # Clip "Z" to -20% and +20%. The clipping is only for the color -- the text will still display the correct numbers. tab_data_clipped = np.clip(tab_data, a_min=MIN_RENDERABLE_PERCENT_CHANGE, a_max=MAX_RENDERABLE_PERCENT_CHANGE) H, W = tab_data.shape hovertext_table = np.empty((H, W), dtype=object) for i in range(H): for j in range(W): cell_text = f"Master: {master_values[i,j]}<br />" cell_text += f"Branch: {branch_values[i,j]} <br />" cell_text += f"Percentage: {tab_data[i,j]}" hovertext_table[i, j] = cell_text redgreen = [RED_HEX, PALE_YELLOW_HEX, GREEN_HEX] colorscale = colorscale_from_list(redgreen) trace = go.Heatmap( z=tab_data_clipped, x=col_labels, y=row_labels, colorscale=colorscale, hoverinfo="text", text=hovertext_table.tolist(), zmin=-MIN_RENDERABLE_PERCENT_CHANGE, zmax=MAX_RENDERABLE_PERCENT_CHANGE, ) layout = go.Layout( title="Percentage Change", font=Font(family="Balto, sans-serif", size=12, color="rgb(68,68,68)"), showlegend=False, xaxis=XAxis(title="", showgrid=True, side="top", tickangle=-45), yaxis=YAxis( title="", autorange="reversed", showgrid=True, ), autosize=False, height=HEATMAP_HEIGHT, width=HEATMAP_WIDTH, margin=Margin(l=135, r=40, b=85, t=170), ) fig = go.Figure(data=[trace], layout=layout) annotations = [] num_rows, num_cols = tab_data.shape for i in range(num_rows): for j in range(num_cols): annotations.append( Annotation( text=str(np.round(tab_data[i, j], 1)) + "%", x=col_labels[j], y=row_labels[i], xref="x1", yref="y1", font=dict(color="rgb(25,25,25)"), showarrow=False, )) fig["layout"].update(annotations=annotations) return fig.to_html(full_html=False, include_plotlyjs="cdn")
def update_graph(interval): zoom = 12.0 latInitial = 37.766083 lonInitial = -122.448649 bearing = 0 venue_list = session.execute( 'select venue_id, latitude, longitude,SUM(visit) AS totalvisit from venuevisitloc GROUP BY venue_id LIMIT 500' ) venue_name = [] venue_visit = [] venue_lat = [] venue_lon = [] for venue in venue_list: venue_name.append(venue.venue_id) venue_visit.append(venue.totalvisit) venue_lat.append(venue.latitude) venue_lon.append(venue.longitude) # to get fixed color range: y = np.array(venue_visit) color = np.array(['rgb(255,255,255)'] * y.shape[0]) for i in range(y.shape[0]): if y[i] < 10: color[i] = 'rgb(166,206,227)' elif y[i] >= 10 and y[i] < 100: color[i] = 'rgb(31,120,180)' elif y[i] >= 100 and y[i] < 200: color[i] = 'rgb(178,223,138)' elif y[i] >= 200 and y[i] < 400: color[i] = 'rgb(51,160,44)' elif y[i] >= 400 and y[i] < 800: color[i] = 'rgb(251,154,153)' else: color[i] = 'rgb(227,26,28)' return go.Figure( data=[ Scattermapbox( # lat=["37.752443", "37.807771", "37.810088", "37.769361", "37.802067", # "40.7127", "40.7589", "40.8075", "40.7489"], # lon=["-122.447543", "-122.473899", "-122.410428", "-122.485742", # "-122.418840", "-74.0134", "-73.9851", "-73.9626", # "-73.9680"], lat=venue_lat, lon=venue_lon, mode='markers', hoverinfo="text", text=venue_visit, #text=["Twin Peaks", "Golden Gate Bridge", # "Pier 39", "Golden Gate Park", # "Lombard Street", "One World Trade Center", # "Times Square", "Columbia University", # "United Nations HQ"], # opacity=0.5, marker=dict( size=8, #color="#ffa0a0" # color = venue_visit, color=color.tolist(), # colorbar=dict( # title='Colorbar' # ), # colorscale = [[0, 'rgb(166,206,227)'], [0.25, 'rgb(31,120,180)'], [0.45, 'rgb(178,223,138)'], [0.65, 'rgb(51,160,44)'], [0.85, 'rgb(251,154,153)'], [1, 'rgb(227,26,28)']], # colorscale='Jet', ), ), ], layout=Layout( autosize=True, height=750, margin=Margin(l=0, r=0, t=0, b=0), showlegend=False, mapbox=dict( accesstoken=mapbox_access_token, center=dict( lat=latInitial, # 40.7272 lon=lonInitial # -73.991251 ), style='dark', bearing=bearing, zoom=zoom)))
def plotly_plot(df_in, x_column, plot_title=None, y_left_label=None, y_right_label=None, bar_plot=False, width=800, height=400, number_of_ticks_display=20, yaxis2_cols=None, x_value_labels=None, modebar_orientation='v', modebar_color='grey', legend_x=None, legend_y=None, title_y_pos=0.9, title_x_pos=0.5, add_crosshairs=True, go_functions=None, opacity_list=None, center_title=True): ya2c = [] if yaxis2_cols is None else yaxis2_cols ycols = [c for c in df_in.columns.values if c != x_column] # create tdvals, which will have x axis labels td = list(df_in[x_column]) if x_column is not None else df_in.index.values nt = len(df_in) - 1 if number_of_ticks_display > len( df_in) else number_of_ticks_display spacing = len(td) // nt tdvals = td[::spacing] tdtext = tdvals if x_value_labels is not None: tdtext = [x_value_labels[i] for i in tdvals] # create data for graph data = [] # iterate through all ycols to append to data that gets passed to go.Figure # for ycol in ycols: # if bar_plot: # b = go.Bar(x=td,y=df_in[ycol],name=ycol,yaxis='y' if ycol not in ya2c else 'y2') # else: # b = go.Scatter(x=td,y=df_in[ycol],name=ycol,yaxis='y' if ycol not in ya2c else 'y2') # data.append(b) # determine if each ycol is of type go.Bar, go.Scatter, etc # pfs = "plot functions" pfs = go_functions if pfs is None: if bar_plot: pfs = [go.Bar for _ in range(len(ycols))] else: pfs = [go.Scatter for _ in range(len(ycols))] # determine each ycol's opacity ops = opacity_list if ops is None: ops = [1 for _ in range(len(ycols))] for i in range(len(ycols)): ycol = ycols[i] b = pfs[i](x=td, y=df_in[ycol], name=ycol, opacity=ops[i], yaxis='y' if ycol not in ya2c else 'y2') data.append(b) # create a layout layout = go.Layout( title=plot_title, xaxis=dict(ticktext=tdtext, tickvals=tdvals, tickangle=45, type='category'), yaxis=dict(title='y main' if y_left_label is None else y_left_label), yaxis2=dict(title='y alt' if y_right_label is None else y_right_label, overlaying='y', side='right'), autosize=True, # autosize=False, # width=width, # height=height, margin=Margin(b=100), modebar={ 'orientation': modebar_orientation, 'bgcolor': modebar_color }) fig = go.Figure(data=data, layout=layout) fig.update_layout( title={ 'text': plot_title, 'y': title_y_pos, 'x': title_x_pos, 'xanchor': 'center', 'yanchor': 'top' }) if (legend_x is not None) and (legend_y is not None): fig.update_layout(legend=dict(x=legend_x, y=legend_y)) if add_crosshairs: fig = figure_crosshairs(fig) if center_title: fig.update_layout(title_x=0.5) return fig
def update_graph(value, slider_value, selectedData, prevLayout, mapControls): zoom = 12.0 latInitial = 40.7272 lonInitial = -73.991251 bearing = 0 listStr = get_lat_lon_color(selectedData, value, slider_value) if (prevLayout is not None and mapControls is not None and 'lock' in mapControls): zoom = float(prevLayout['mapbox']['zoom']) latInitial = float(prevLayout['mapbox']['center']['lat']) lonInitial = float(prevLayout['mapbox']['center']['lon']) bearing = float(prevLayout['mapbox']['bearing']) return go.Figure( data=Data([ Scattermapbox( lat=eval(listStr)['Lat'], lon=eval(listStr)['Lon'], mode='markers', hoverinfo="lat+lon+text", text=eval(listStr).index.hour, marker=go.Marker(color=np.append( np.insert(eval(listStr).index.hour, 0, 0), 23), colorscale=[[0, 'rgb(153,236,21)'], [0.04167, 'rgb(218,240,23)'], [0.0833, 'rgb(187,236,25)'], [0.125, 'rgb(157,232,27)'], [0.1667, 'rgb(128,228,29)'], [0.2083, 'rgb(102,224,31)'], [0.25, 'rgb(76,220,32)'], [0.292, 'rgb(52,216,34)'], [0.333, 'rgb(36,210,73)'], [0.375, 'rgb(37,208,66)'], [0.4167, 'rgb(38,204,88)'], [0.4583, 'rgb(40,200,109)'], [0.50, 'rgb(41,196,129)'], [0.54167, 'rgb(42,192,147)'], [0.5833, 'rgb(43,188,164)'], [1.0, 'rgb(97,48,153)']], opacity=0.5, size=5, colorbar=dict(thicknessmode="fraction", title="Time of<br>Day", x=0.935, xpad=0, nticks=24, tickfont=dict(color='white'), titlefont=dict(color='white'), titleside='right')), ), Scattermapbox( lat=[ "40.7505", "40.8296", "40.7484", "40.7069", "40.7527", "40.7127", "40.7589", "40.8075", "40.7489" ], lon=[ "-73.9934", "-73.9262", "-73.9857", "-74.0113", "-73.9772", "-74.0134", "-73.9851", "-73.9626", "-73.9680" ], mode='markers', hoverinfo="text", text=[ "Madison Square Garden", "Yankee Stadium", "Empire State Building", "New York Stock Exchange", "Grand Central Station", "One World Trade Center", "Times Square", "Columbia University", "United Nations HQ" ], # opacity=0.5, marker=go.Marker(size=6, color="#ffa0a0"), ), ]), layout=Layout( autosize=True, height=750, margin=Margin(l=0, r=0, t=0, b=0), showlegend=False, mapbox=dict( accesstoken=mapbox_access_token, center=dict( lat=latInitial, # 40.7272 lon=lonInitial # -73.991251 ), style='dark', bearing=bearing, zoom=zoom), updatemenus=[ dict(buttons=([ dict(args=[{ 'mapbox.zoom': 12, 'mapbox.center.lon': '-73.991251', 'mapbox.center.lat': '40.7272', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='Reset Zoom', method='relayout') ]), direction='left', pad={ 'r': 0, 't': 0, 'b': 0, 'l': 0 }, showactive=False, type='buttons', x=0.45, xanchor='left', yanchor='bottom', bgcolor='#323130', borderwidth=1, bordercolor="#6d6d6d", font=dict(color="#FFFFFF"), y=0.02), dict(buttons=([ dict(args=[{ 'mapbox.zoom': 15, 'mapbox.center.lon': '-73.9934', 'mapbox.center.lat': '40.7505', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='Madison Square Garden', method='relayout'), dict(args=[{ 'mapbox.zoom': 15, 'mapbox.center.lon': '-73.9262', 'mapbox.center.lat': '40.8296', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='Yankee Stadium', method='relayout'), dict(args=[{ 'mapbox.zoom': 15, 'mapbox.center.lon': '-73.9857', 'mapbox.center.lat': '40.7484', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='Empire State Building', method='relayout'), dict(args=[{ 'mapbox.zoom': 15, 'mapbox.center.lon': '-74.0113', 'mapbox.center.lat': '40.7069', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='New York Stock Exchange', method='relayout'), dict(args=[{ 'mapbox.zoom': 15, 'mapbox.center.lon': '-73.785607', 'mapbox.center.lat': '40.644987', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='JFK Airport', method='relayout'), dict(args=[{ 'mapbox.zoom': 15, 'mapbox.center.lon': '-73.9772', 'mapbox.center.lat': '40.7527', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='Grand Central Station', method='relayout'), dict(args=[{ 'mapbox.zoom': 15, 'mapbox.center.lon': '-73.9851', 'mapbox.center.lat': '40.7589', 'mapbox.bearing': 0, 'mapbox.style': 'dark' }], label='Times Square', method='relayout') ]), direction="down", pad={ 'r': 0, 't': 0, 'b': 0, 'l': 0 }, showactive=False, bgcolor="rgb(50, 49, 48, 0)", type='buttons', yanchor='bottom', xanchor='left', font=dict(color="#FFFFFF"), x=0, y=0.05) ]))
def plotly_plot(df_in,x_column,plot_title=None, y_left_label=None,y_right_label=None, bar_plot=False,width=800,height=400, number_of_ticks_display=20, yaxis2_cols=None, x_value_labels=None, modebar_orientation='v',modebar_color='grey', legend_orientation='h', autosize=True): ya2c = [] if yaxis2_cols is None else yaxis2_cols ycols = [c for c in df_in.columns.values if c != x_column] # create tdvals, which will have x axis labels # td = list(df_in[x_column]) td = df_in[x_column].values nt = len(df_in)-1 if number_of_ticks_display > len(df_in) else number_of_ticks_display spacing = len(td)//nt tdvals = td[::spacing] tdtext = tdvals if x_value_labels is not None: tdtext = [x_value_labels[i] for i in tdvals] # create data for graph data = [] # iterate through all ycols to append to data that gets passed to go.Figure for ycol in ycols: if bar_plot: b = go.Bar(x=td,y=df_in[ycol],name=ycol,yaxis='y' if ycol not in ya2c else 'y2') else: b = go.Scatter(x=td,y=df_in[ycol],name=ycol,yaxis='y' if ycol not in ya2c else 'y2') data.append(b) # create a layout layout = go.Layout( title=plot_title, xaxis=dict( ticktext=tdtext, tickvals=tdvals, tickangle=45, type='category', showspikes=True, spikemode='toaxis+across', spikedash='solid', spikethickness=1, ), yaxis=dict( title='y main' if y_left_label is None else y_left_label, showspikes=True, spikemode='toaxis+across', spikedash='solid', spikethickness=1, ), yaxis2=dict( title='y alt' if y_right_label is None else y_right_label, overlaying='y', side='right'), autosize=autosize, # autosize=False, # width=width, # height=height, margin=Margin( b=100 ), modebar={'orientation': modebar_orientation,'bgcolor':modebar_color}, hovermode='x', spikedistance=1000 ) fig = go.Figure(data=data,layout=layout) layout_legend = {} if legend_orientation == 'v' else {'orientation':legend_orientation,'x':0, 'y':1.1} fig.update_layout( title={ 'text': plot_title, 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}, # legend={'orientation':legend_orientation,'x':0, 'y':1.1}, legend=layout_legend, ) return fig
def plotly_plot(df_in, x_column, plot_title=None, y_left_label=None, y_right_label=None, bar_plot=False, figsize=(16, 10), number_of_ticks_display=20, yaxis2_cols=None): ''' Return a plotly Figure that you can use with iplot, to produce multi-axis x/y scatter and bar graphs :param df_in: data frame with a single x, and multiple y values to graph :param x_column: the column in df_in that holds the x-axis values :param plot_title: title of plot :param y_left_label: :param y_right_label: :param bar_plot: If True, plot bars, other wise, plot x/y scatter line :param figsize: :param number_of_ticks_display: Number of x axis major ticks to display :param yaxis2_cols: the dataframe columns that hold the y values for the second y axis, if any ''' ya2c = [] if yaxis2_cols is None else yaxis2_cols ycols = [c for c in df_in.columns.values if c != x_column] # create tdvals, which will have x axis labels td = list(df_in[x_column]) nt = len(df_in) - 1 if number_of_ticks_display > len( df_in) else number_of_ticks_display spacing = len(td) // nt tdvals = td[::spacing] # create data for graph data = [] # iterate through all ycols to append to data that gets passed to go.Figure for ycol in ycols: if bar_plot: b = go.Bar(x=td, y=df_in[ycol], name=ycol, yaxis='y' if ycol not in ya2c else 'y2') else: b = go.Scatter(x=td, y=df_in[ycol], name=ycol, yaxis='y' if ycol not in ya2c else 'y2') data.append(b) # create a layout layout = go.Layout( title=plot_title, xaxis=dict(ticktext=tdvals, tickvals=tdvals, tickangle=45, type='category'), yaxis=dict(title='y main' if y_left_label is None else y_left_label), yaxis2=dict(title='y alt' if y_right_label is None else y_right_label, overlaying='y', side='right'), margin=Margin(b=100)) fig = go.Figure(data=data, layout=layout) return fig