def update_graph(cleaned_data): df_t = pd.read_json(cleaned_data, orient='split') print("lenght of df is ", len(df_t)) if (len(df_t) == 0): return { 'data': [ go.Table(header=dict(values=['Message']), cells=dict(values=[['No data']])) ] } y1 = list(df_t['Total Actual']) y2 = list(df_t['Total Target']) indname = list(df_t['Indicator']) return { 'data': [ go.Bar(x=indname, y=y1, name='achieved', marker=go.Marker(color='#07d7a7')), go.Bar(x=indname, y=y2, name='target', marker=go.Marker(color='#ff9f00')) ] }
def getGlobalDataByDateRange(df, country, start=1750, end=2015): maxAllowed = df[df['dt'] == 1850]['LandAverageTemperature'] + 2 y = df[(df['dt'] > start) & (df['dt'] <= end)]['LandAverageTemperature'] x = df[(df['dt'] > start) & (df['dt'] <= end)]['dt'] xi = arange(0, len(x)) # Generated linear fit slope, intercept, _, _, _ = stats.linregress(xi, y) line = slope * xi + intercept trace1 = go.Scatter(x=x, y=y, mode='markers', marker=go.Marker(color='rgb(255, 204, 153)'), name='Temperature scatter') trace2 = go.Scatter(x=x, y=line, mode='lines', marker=go.Marker(color='rgb(255, 153, 51)'), name='Fitted line') traceMax = go.Scatter(x=x, y=[maxAllowed[0]] * len(x), line=dict(color=('rgb(205, 12, 24)'), width=2, dash='dot'), name='Maximum allowed temperature') return [trace1, trace2, traceMax]
def callback_drug_reports_at_ages_bars(value): series = (data.query('drug_concept_name == @value').groupby( ['age_cat']).apply(lambda x: x.shape[0])) x = series.index.tolist() y = series.values y_norm = np.round((series.values / series.sum()) * 100, 0) drug_trace = go.Bar(x=x, y=y_norm, name='{}'.format(value), text=['{} reports'.format(i) for i in y], marker=go.Marker(color='rgb(55, 83, 109)')) all_trace = go.Bar( x=all_age_cat_counts_x, y=all_age_cat_counts_y_norm, name='All drugs', text=['{} reports'.format(i) for i in all_age_cat_counts_y], marker=go.Marker(color='rgb(180,180,180)')) return { 'data': [all_trace, drug_trace], 'layout': go.Layout(title='Patients taking {} at different age intervals'.format( value), showlegend=True, yaxis=dict(title="Percentage of reports", type='-'), xaxis=dict(title="Age category"), legend=go.Legend(x=0, y=1.0), margin=go.Margin(l=40, r=20, t=40, b=100)) }
def line_per_odper_fitting_fuction(dataframe, function, filename): """line graph for long tail analysis. X: percentage Y: od percentage""" # calculate new x's and y's x_new = np.linspace(0.5, 1, 50) y_new = function(x_new) data_origin = go.Scatter( x=dataframe['percentage'], # assign x as the dataframe column 'x' y=dataframe['od_needed'], mode='markers', marker=go.Marker(color='rgb(255, 127, 14)'), name='Data') data_fitting = go.Scatter(x=x_new, y=y_new, mode='lines', marker=go.Marker(color='rgb(31, 119, 180)'), name='Fit') data = [data_origin, data_fitting] layout = go.Layout( title='Coverage and OD Relationship with Polynomial Fit in Python', plot_bgcolor='rgb(229, 229, 229)', xaxis=go.XAxis(zerolinecolor='rgb(255,255,255)', gridcolor='rgb(255,255,255)'), yaxis=go.YAxis(zerolinecolor='rgb(255,255,255)', gridcolor='rgb(255,255,255)')) fig = go.Figure(data=data, layout=layout) py.plot(fig, filename=filename)
def _update_graph(map_style, region): dff = dataframe radius_multiplier = {'inner': 1.5, 'outer': 3} layout = go.Layout( title=metadata['title'], autosize=True, hovermode='closest', height=750, font=dict(family=theme['font-family']), margin=go.Margin(l=0, r=0, t=45, b=10), mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=regions[region]['lat'], lon=regions[region]['lon'], ), pitch=0, zoom=regions[region]['zoom'], style=map_style, ), ) data = go.Data([ # outer circles represent magnitude go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['outer'], colorscale=colorscale_magnitude, color=dff['Magnitude'], opacity=1, ), text=dff['Text'], # hoverinfo='text', showlegend=False, ), # inner circles represent depth go.Scattermapbox( lat=dff['Latitude'], lon=dff['Longitude'], mode='markers', marker=go.Marker( size=dff['Magnitude'] * radius_multiplier['inner'], colorscale=colorscale_depth, color=dff['Depth'], opacity=1, ), # hovering behavior is already handled by outer circles hoverinfo='skip', showlegend=False ), ]) figure = go.Figure(data=data, layout=layout) return figure
def createFigure(filename, isAutoOpen=True, isUploadToServer=False): # ------------Custom Candlestick Colors------------ # Make increasing ohlc sticks and customize their color and name opens = [datarow.open for datarow in dataRows] highs = [datarow.high for datarow in dataRows] lows = [datarow.low for datarow in dataRows] closes = [datarow.close for datarow in dataRows] fig_increasing = FigureFactory.create_candlestick( opens, highs, lows, closes, dates=datetime_xAxis, direction='increasing', marker=go.Marker(color='rgb(61, 153, 112)'), line=go.Line(color='rgb(61, 153, 112)')) # Make decreasing ohlc sticks and customize their color and name fig_decreasing = FigureFactory.create_candlestick( opens, highs, lows, closes, dates=datetime_xAxis, direction='decreasing', marker=go.Marker(color='rgb(255, 65, 54)'), line=go.Line(color='rgb(255, 65, 54)')) # Initialize the figure fig = fig_increasing fig['data'].extend(fig_decreasing['data']) # ------------Add extensions------------ for index, extensionList in enumerate(extensionLists): addLineExtension(fig, [data[0] for data in extensionList], [data[1] for data in extensionList], extensionNames[index], extensionLineTypes[index], extensionColors[index]) # ------------Update layout And Draw the chart------------ filename = chartTitle fig['layout'].update( title=filename, xaxis=dict(ticktext=[datarow.date for datarow in dataRows], tickvals=datetime_xAxis, showticklabels=False, showgrid=True, showline=True), ) plotly.offline.plot(fig, filename=filename + '.html', auto_open=isAutoOpen) print "----------The chart has been generated----------\n"
def update_plot(n): if n < 182: x = l_df['index'] y = l_df['Count'] x = np.array(x) y = np.array(y) x = x[:n] y = y[:n] if (n - 1) % 12 == 0: t_val.append(n) t_lab.append(l_df['YEAR'][n]) # calculate polynomial z = np.polyfit(x, y, 3) f = np.poly1d(z) # calculate new x's and y's x_new = np.linspace(x[0], x[-1], len(x) * 10) y_new = f(x_new) # Creating the dataset, and generating the plot trace1 = go.Scatter(x=x, y=y, mode='markers', marker=go.Marker(color='rgb(255, 127, 14)'), name='Data') trace2 = go.Scatter(x=x_new, y=y_new, mode='lines', marker=go.Marker(color='rgb(31, 119, 180)'), name='Fit') layout = go.Layout(title='Overall Crime Trend in Vancouver', titlefont=dict(size=22), plot_bgcolor='rgb(248, 249, 247)', xaxis=go.XAxis(zerolinecolor='rgb(255,255,255)', gridcolor='rgb(255,255,255)', title='Time', titlefont=dict(size=16), tickvals=t_val, ticktext=t_lab, tickfont=dict(size=14, color='blue')), yaxis=go.YAxis(zerolinecolor='rgb(255,255,255)', gridcolor='rgb(255,255,255)', title='Crime Counts', titlefont=dict(size=16))) data = [trace1, trace2] return {'data': data, 'layout': layout}
def display_map(coordinates_for_map, mapbox_token): job_locations = gr.Data([ gr.Scattermapbox(lat=coordinates_for_map.latitude, lon=coordinates_for_map.longitude, mode='markers', marker=gr.Marker(size=12, color='rgb(24, 108, 168)', opacity=0.7), text=coordinates_for_map['info'] + '<br>Jobs available in this area: ' + coordinates_for_map['JobCount'], hoverinfo='text') ]) map_layout = gr.Layout(title='Jobs in the MA/RI Area', autosize=True, hovermode='closest', showlegend=False, mapbox=dict(accesstoken=mapbox_token, bearing=0, center=dict(lat=42.4072, lon=-71.3824), pitch=10, zoom=7, style='light')) coordinates_for_map = dict(data=job_locations, layout=map_layout) pl.plot(coordinates_for_map, filename='stackoverflow_jobs_map.html')
def update_figure(opt): xi = df1[opt] y = df1['Salary'] slope, intercept, r_value, p_value, std_err = stats.linregress(xi, y) line = slope * xi + intercept plot1 = go.Scatter(x=df1[opt], y=df1['Salary'], mode='markers', line=dict(width=2, color='rgb(229, 151, 50)'), name='Actual Distribution of "{}"'.format(opt)) plot2 = go.Scatter(x=df1[opt], y=line, mode='lines', marker=go.Marker(color='rgb(31, 119, 180)'), name='Salary') layout = go.Layout(title='Regression Analysis Graph', hovermode='closest', xaxis={'title': 'Age'}) fig = go.Figure(data=[plot1, plot2], layout=layout) return fig
def pcaWiki(self,file): self.formDataPCA(file) X_std = StandardScaler().fit_transform(self.X) sklearn_pca = sklearnPCA(n_components=2) Y_sklearn = sklearn_pca.fit_transform(X_std) traces = [] for name in self.names: trace = go.Scatter( x=Y_sklearn[self.y==name,0], y=Y_sklearn[self.y==name,1], mode='markers', name=name, marker=go.Marker( size=12, line=go.Line( color='rgba(217, 217, 217, 0.14)', width=0.5), opacity=0.8)) traces.append(trace) data = go.Data(traces) layout = go.Layout(xaxis=go.XAxis(title='PC1', showline=False), yaxis=go.YAxis(title='PC2', showline=False)) fig = go.Figure(data=data, layout=layout) if (self.outputType == 'file'): print(py.plot(fig,filename='pca')) else: return (py.plot(fig,include_plotlyjs='False',output_type='div'))
def getGlobalDataByDateRange(co2, start = 1960, end = 2016): x = co2[(co2['Year'] > start) & (co2['Year'] <= end)]['Year'] y_co2 = co2[(co2['Year'] > start) & (co2['Year'] <= end)]['Global'] co2goal = float((co2[co2['Year'] == 1990]['Global']) / 2) traceCO2 = go.Scatter( x=x, y=co2['Global'], mode='lines', marker=go.Marker(color='rgb(255, 153, 51)'), name='CO₂ emmission' ) lineCO2 = go.Scatter( x=x, y=[co2goal] * len(x), line = dict( color = ('rgb(205, 12, 24)'), width = 2, dash = 'dot'), name='CO₂ Goal' ) return [traceCO2, lineCO2]
def line_trace_course_fr_diff(course_name, colour, semester=None, dash_type=None, showlegend=True): qry = qry_location_diff_history(course_name) df1 = db_extract_query_to_dataframe(qry, postgres_cur, print_messages=False) if semester == 1: df1 = df1.loc[df1['semester'] == 1] elif semester == 2: df1 = df1.loc[df1['semester'] == 2] x = [i - 0.5 for i in range(1, 7)] # Create Semester 1 trace (solid) trace = go.Scatter( x=x, y=df1['fr_diff'].tolist(), name='<span style="color: {1}"> {0} </span>'.format( course_name, colour), text=None, textfont={ 'size': 14, 'color': colour }, line=go.Line(width=3, color=colour, dash=dash_type), marker=go.Marker(color=colour, size=10, symbol='diamond'), connectgaps=False, mode='markers', showlegend=showlegend, textposition='bottom right', ) return trace
def spain_corruption_evolution(): spain_corruption_filter_data = spain_corruption[ (spain_corruption['year'] >= 2000) & (spain_corruption['year'] <= 2011)] yvalues = [ records[1] for records in spain_corruption_filter_data.groupby( ['year']).count().to_records() ] xvalues = [ records[0] for records in spain_corruption_filter_data.groupby( ['year']).count().to_records() ] return dcc.Graph(figure=go.Figure(data=[ go.Bar( x=xvalues, y=yvalues, marker=go.Marker(color='rgb(55, 83, 109)'), ) ], layout=go.Layout( title='Corruption Cases per Year', showlegend=False, margin=go.Margin(l=40, r=0, t=40, b=30))), style={'height': 300}, id='my-graph')
def pca(self,winSize): data = np.zeros((len(self.data),len(self.data['FUNC'][winSize]))) i=0 for dEl in sorted(self.data): self.data[dEl][winSize] = normalizeMaxMin(self.data[dEl][winSize]) data[i] = self.data[dEl][winSize] i+=1 X_std = StandardScaler().fit_transform(np.transpose(data)) sklearn_pca = sklearnPCA(n_components=2) Y_sklearn = sklearn_pca.fit_transform(X_std) traces = [] trace = go.Scatter( x=Y_sklearn[:,0], y=Y_sklearn[:,1], mode='markers', marker = go.Marker( size=12, line= go.Line( color='rgba(217, 217, 217, 0.14)', width=0.5), opacity=0.8)) traces.append(trace) data = go.Data(traces) layout = go.Layout(xaxis = go.XAxis(title='PC1', showline=False), yaxis = go.YAxis(title='PC2', showline=False)) fig = go.Figure(data=data, layout=layout) if self.outputType=='file': print(py.plot(fig, filename='pca.html')) else: return py.plot(fig, output_type='div')
def build_nodes(_G, _generation): nodes = _G.nodes(data=True) _node_trace = go.Scatter( x=[pos[node[0]][0] for node in nodes], y=[pos[node[0]][1] for node in nodes], name='gen %d' % _generation, text=[x[1]['probs'] for x in nodes], mode='markers', visible=True if _generation == 0 else 'legendonly', hoverinfo='text', marker=go.Marker( showscale=True, color=[x[1]['color'] for x in nodes], colorscale='RdBu', colorbar=dict( title='Assurance', xpad=100, ), cmin=0., # minimum color value cmax=1., # maximum color value cauto=False, # do not automatically fit color values reversescale=False, size=15, line=dict(width=2))) return _node_trace
def multixic(plotData, timeunit='s'): """ Args: plotData: [(xic_x, xic_y, pts_x, pts_y),] timeunit: label string default = 's' Returns: plotly graph object """ traces = [] for xic_x, xic_y, pts_x, pts_y in plotData: traces.append(go.Scatter(x=xic_x, y=xic_y, mode='line', name='xic')) traces.append( go.Scatter(x=pts_x, y=pts_y, marker=go.Marker(size=10, color='black', symbol='triangle-down'), mode='markers', name='ms/ms points')) layout = dict( title='XIC', xaxis=dict(title='time ({})'.format(timeunit)), yaxis=dict(title='Intensity'), ) fig = go.Figure(data=traces, layout=layout) plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div
def location_tracker(name): lat, lon = current_location(name) weather_type, celsius, wind_speed = show_climate(name) lat = str(lat) lon = str(lon) data = go.Data([ go.Scattermapbox( lat=[lat], lon=[lon], mode='markers', marker=go.Marker(size=11), text=[ str(name).title() + ' ' + str(weather_type) + ' ' + str(celsius) + ' C ' + str(wind_speed) + ' mph' ], #hoverlabel=dict(bgcolor='rgba(188, 20, 26, 0.5)'), hoverinfo='text') ]) layout = go.Layout( #width=600, height=620, autosize=True, showlegend=False, hovermode='closest', mapbox=dict(accesstoken=access, bearing=1, center=dict(lat=int(lat.split('.')[0]), lon=int(lon.split('.')[0])), pitch=0, zoom=6, style='dark'), ) return {'data': data, 'layout': layout}
def plot_destinations(df_plotting): df_plotting = df_plotting.sort_values(by='count') sizes = np.sqrt(df_plotting['count']) + 3 cluster_colors = np.log(df_plotting['count']) fig = go.Figure(data = [go.Scattermapbox(lat=df_plotting["latitude"], lon=df_plotting["longitude"], mode='markers', text="User ID: " + df_plotting["user_id"].apply(str) + "<br>Destination ID: " + df_plotting["cluster_assignment"].apply(str) + "<br># Stops: " + df_plotting["count"].apply(str), textposition='bottom', marker=go.Marker(size=sizes, opacity = 1, color=cluster_colors)) ], layout = go.Layout(autosize=False, width=640, height=300, margin=go.Margin( l=0, r=0, b=0, t=0, pad=0), hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=df_plotting["latitude"].median(), lon=df_plotting["longitude"].median()), pitch=0, style='light', zoom=9.5))) return fig
def plotly_scatter(x, y, mask_by=None, hover_text=None, xlab='', ylab='', main='', colorscale='Viridis', mask_title=''): data = go.Scatter( x=x, y=y, mode='markers') if hover_text is not None: data['text'] = hover_text if mask_by is not None: data.marker = go.Marker( colorbar=go.ColorBar( title=mask_title, titleside='right'), color=mask_by, colorscale=colorscale, showscale=True, opacity=0.7) trace = [data] layout = go.Layout( title=main, xaxis=dict(title=xlab, autorange=True), yaxis=dict(title=ylab, scaleanchor='x', autorange=True), height=600, width=600) fig = go.Figure(data=trace, layout=layout) # ST's y should be reversed to match the H&E image fig.layout.yaxis.autorange = 'reversed' return fig
def build_figure(layers_ls, year, colorscl=colorscl, mapbox_access_token=None, name='image.png'): data = go.Data([ go.Scattermapbox(lat=[0], lon=[0], marker=go.Marker(cmax=5000, cmin=0, colorscale=colorscl, showscale=True, autocolorscale=False, color=range(0, 5000), colorbar=go.ColorBar(len=.89)), mode='markers') ]) layout = go.Layout( title='{}'.format(year), height=1050, width=800, autosize=True, hovermode='closest', mapbox=dict(layers=layers_ls, accesstoken=mapbox_access_token, bearing=0, center=dict(lat=39.03, lon=-105.7), pitch=0, zoom=5.5, style='light'), ) fig = dict(data=data, layout=layout) py.image.save_as(fig, filename=name, width=750, height=575)
def getscatterobj(xobjname, yobjname): """ Constructs a 2-D Scatter trace object where each point is a combination of the objective score for objective 'xobjname' and of the objective score of objective 'yobjname'. :param xobjname: objective score for the horizontal axis :param yobjname: objective score for the vertical axis :return: plotly Scatter object """ x = [] y = [] ranktext = [] for item in self.objSpace: x.append(item[xobjname]) y.append(item[yobjname]) ranktext.append('rank: ' + str(item['goldberg'])) return grob.Scatter(x=x, y=y, text=ranktext, marker=grob.Marker(symbol='cross', color='rgb(237,0,178)', size=6), mode='markers', name='{:s} v {:s}'.format(xobjname, yobjname), opacity=0.7)
def plot_scatter_dynamicTraces(datasets, datasets_labels, datsets_colors, title): traces = [] for x in xrange(0, len(datasets)): traces.append( go.Scatter(x=datasets[x]['path_lenght_total_meters'], y=datasets[x]['computation_time_millis'], mode='markers', marker=go.Marker(color=datsets_colors[x]), name=datasets_labels[x])) layout = go.Layout( title=title, xaxis=dict(title='Distance between points (in meters)', titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')), yaxis=dict(title='Computation time (seconds)', titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f'))) fig = dict(data=traces, layout=layout) plotly.offline.iplot(fig, filename='./scatter_time_vs_pathLength', image='png') pio.write_image(fig, '/home/mfaria/Downloads/plot_scatter_dynamicTraces.svg', scale=2)
def make_trace(df, package, rgb): x_date = df["commit_date"] y_package = df[package] return go.Trace(x=x_date, y=y_package, name=package, marker=go.Marker(color=rgb))
def create_polyFitTrace(data, trace_color, polynomial_degree, start, label, legend=True): # calculate polynomial x_original = data['path_lenght_total_meters'] y_original = data['computation_time_millis'] z = np.polyfit(x_original, y_original, polynomial_degree) f = np.poly1d(z) # calculate new x's and y's x_new = np.linspace(start, max(x_original) + 5, 120) y_new = f(x_new) degree_sym = u'\u00b0'.encode('utf-8').strip() trace = go.Scatter(x=x_new, y=y_new, mode='lines', marker=go.Marker(color=trace_color), name=str(polynomial_degree) + degree_sym + ' poly fit of ' + label, showlegend=legend) return trace
def update_map(n_clicks, selected_sqft, hoverData, selected_cp, selected_beds, selected_ds, selected_types, toggle): column = {2: 'ClosingPrice', 1: 'DollarSqFt'}[toggle] date = hoverData['points'][0]['x'] date_y = pd.to_datetime(date) start = date_y - datetime.timedelta(365) end = date_y + datetime.timedelta(35) year_labels = df['ClosingDate'].between(start, end) if selected_cp[1] > 9500000: selected_cp[1] = df['ClosingPrice'].max() + 1 if selected_ds[1] > 7500: selected_ds[1] = df['DollarSqFt'].max() + 1 if selected_sqft[1] > 7500: selected_sqft[1] = df['SqFt'].max() beds_labels = mult_selections(selected_beds, 'Beds', df) closing_price_labels = (df['ClosingPrice'] < selected_cp[1]) & ( df['ClosingPrice'] > selected_cp[0]) sqft_labels = (df['SqFt'] < selected_sqft[1]) & (df['SqFt'] > selected_sqft[0]) dollarsqft_label = (df['DollarSqFt'] < selected_ds[1]) & (df['DollarSqFt'] > selected_ds[0]) types_labels = mult_selections(np.array(selected_types), 'Type', df) labels_1 = beds_labels & closing_price_labels & sqft_labels & dollarsqft_label & types_labels & year_labels df_output = df.loc[labels_1][['Lat', 'Lng', 'SellersAgent1', column]] c_min = df_output[column].min() c_range = df_output[column].max() - c_min df_output['color'] = df_output[column].apply(gen_color, args=[c_range, c_min]) data = go.Data([ go.Scattermapbox(lat=df_output['Lat'], lon=df_output['Lng'], mode='markers', marker=go.Marker(size=7, opacity=0.6, color=df_output['color']), text=df_output[column].apply(intWithCommas)) ]) layout = go.Layout( autosize=False, width=1300, height=800, hovermode='closest', mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict(lat=40.717086, lon=-73.991040), pitch=0, zoom=10, style='dark'), ) return dict(data=data, layout=layout)
def plot_stops(df_plotting): fig = go.Figure(data = [go.Scattermapbox(lat=df_plotting["latitude"], lon=df_plotting["longitude"], mode='markers', text="User ID: " + df_plotting["user_id"].apply(str), textposition='bottom', marker=go.Marker(size=5,opacity = 1, color='orange')) ], layout = go.Layout(autosize=False, width=640, height=300, margin=go.Margin( l=0, r=0, b=0, t=0, pad=0), hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=dict( lat=df_plotting["latitude"].median(), lon=df_plotting["longitude"].median()), pitch=0, style='light', zoom=9.5))) return fig
def create_geo(summary_polyline): gps = polyline.decode(summary_polyline) df = pd.DataFrame(gps, columns=['lat', 'long']) df['cnt'] = 1 data = go.Data([ go.Scattermapbox(lat=df.lat, lon=df.long, mode='lines', hoverinfo='text', marker=go.Marker(size=17, color='rgb(255, 0, 0)', opacity=0.7)) ]) layout = go.Layout( autosize=False, hovermode='closest', showlegend=False, mapbox=dict(accesstoken=mapbox_access_token, bearing=0, center=dict(lat=df.lat[int(len(df) / 4)], lon=df.long[int(len(df) / 4)]), pitch=0, zoom=10.5, style='light'), ) fig = dict(data=data, layout=layout) return fig
def popularGraph(yearRange, gender): filteredDf = df[(df.Year >= yearRange[0]) & (df.Year <= yearRange[1]) & (df.Gender == 'M')].groupby( ['Name', 'Gender'], as_index=False)[['n']].sum().sort_values( ["n"], ascending=False).iloc[:10, ] girlsDf = df[(df.Year >= yearRange[0]) & (df.Year <= yearRange[1]) & (df.Gender == 'F')].groupby( ['Name', 'Gender'], as_index=False)[['n']].sum().sort_values( ["n"], ascending=False).iloc[:10, ] babyBlue = ['rgb(137, 207, 240)'] * 10 babyPink = ['rgb(244, 194, 194)'] * 10 myColors = babyBlue if gender == 'E': filteredDf = pd.concat([filteredDf, girlsDf]) myColors.extend(babyPink) elif gender == 'F': filteredDf = girlsDf myColors = babyPink traces = [ go.Bar(x=filteredDf.Name, y=filteredDf.n, name='Total Count', marker=go.Marker(color=myColors)) ] return { 'data': traces, 'layout': go.Layout(title='Popular US Names', margin=go.Margin(l=40, r=40, t=40, b=40)) }
def map_plotter(strata): try: graphs = [] for st in strata: lats, lons, last_name = clustering(strata) graphs.append( go.Scattermapbox(lat=lats, lon=lons, mode='marker', marker=go.Marker(size=6, color='rgb(255, 0, 0)', opacity=0.7), text=last_name, hoverinfo='text')) layout = go.Layout( height=800, #width=500, title='Volcanoes', autosize=True, hovermode='closest', showlegend=False, mapbox=dict(accesstoken=token, bearing=0, pitch=0, zoom=1.2, style='light'), ) fig = {'data': graphs, 'layout': layout} return fig except Exception as e: with open('errors.txt', 'w') as error: error.write(str(e))
def gen_second_graph(interval): var = data.percent('Price') trace = go.Bar( y=var.tail(n=10).Price, x=var.tail(n=10).index, width=[3000 for i in range(len(var.tail(n=10)))], marker=go.Marker(color=[ '#009688' if var.tail(n=10).Price[i] > 0 else '#b71c1c' for i in range(len(var.tail(n=10))) ]), hoverinfo='Δ%', ) layout = go.Layout(height=200, xaxis=dict(range=[ data.data.tail(n=10).index.min(), data.data.tail(n=10).index.max() ], showgrid=True, showline=True, zeroline=False, fixedrange=False, title='Test'), margin=go.Margin(t=0, l=100, r=100)) return go.Figure(data=[trace], layout=layout)