def plot_val_train_loss_plotly(history): training_loss = history.history['loss'] validation_loss = history.history['val_loss'] # FIXME: epoch_range = range(1, len(training_loss) + 1) loss_train = go.Scatter(x=epoch_range, y=training_loss, mode='lines', name='training loss', line=dict(color=('rgb(22, 96, 167)'), width=4, dash='dot')) loss_val = go.Scatter(x=epoch_range, y=validation_loss, mode='lines', name='validation loss', line=dict(color=('rgb(205, 12, 24)'), width=4)) data = [loss_train, loss_val] layout = dict( title='Loss vs. Epochs', xaxis=dict(title='Epochs'), yaxis=dict(title='Loss'), ) fig = dict(data=data, layout=layout) py.iplot(fig, filename='basic-line')
def plot_LDA(data, features): X = data[features] y = data["categoria"] X_std = StandardScaler().fit_transform(X) LDA = LinearDiscriminantAnalysis() Y = LDA.fit_transform(X_std, y) results = [] for name in (2, 3, 13): result = go.Scatter(x=Y[y == name, 0], y=Y[y == name, 1], mode="markers", name=name, marker=go.Marker(size=8, line=go.Line( color="rgba(225,225,225,0.2)", width=0.5), opacity=0.75)) results.append(result) data = go.Data(results) layout = go.Layout(xaxis=go.XAxis(title="CP1", showline=False), yaxis=go.YAxis(title="CP2", showline=False)) fig = go.Figure(data=data, layout=layout) py.iplot(fig) return fig
def plotter_sankey(label, color, source, target, value, color_links, title, create_html=False, host_online=False): import plotly.graph_objects as go fig = go.Figure(data=[ go.Sankey( node=dict(pad=3, thickness=15, line=dict(color="green", width=0.), label=label, color=color), link=dict( source=source, target=target, value=value, color=color_links)) ]) fig.update_layout(title_text=title, font_size=14) fig.show() if create_html: import plotly.io as pio pio.write_html(fig, file='figures/' + title + '.html', auto_open=True) if host_online: import chart_studio.plotly as py py.iplot(fig, filename=title)
def plotly_histogram2(X, columns, target): colors = { 2: 'rgb(255,127,20)', 3: 'rgb(31, 220, 120)', 13: 'rgb(44, 50, 180)' } traces = [] _targets = sorted(X[target].unique().tolist()) legend = {2: True, 3: True, 13: True} for col in range(2): for key in range(len(_targets)): traces.append( go.Histogram(x=X[X[target] == _targets[key]][columns[col]], opacity=0.7, xaxis="x%s" % (col + 1), marker=go.Marker(color=colors[_targets[key]]), name=_targets[key], showlegend=legend[_targets[key]])) legend = {2: False, 3: False, 13: False} data = go.Data(traces) layout = go.Layout(barmode="overlay", xaxis=go.XAxis(domain=[0, 0.48], title=columns[0]), xaxis2=go.XAxis(domain=[0.52, 1], title=columns[1]), yaxis=go.YAxis(title="Numero de Defectos"), title="Histograma caracteristicas") fig = go.Figure(data=data, layout=layout) py.iplot(fig) return fig
def plot_rolling_ff(strat, factors = None, rolling_window = 36, online = False, plt_type = 'iplot', rng = [-4,4], width = 600, height = 400): ff_facs = get_ff_rolling_factors(strat, factors, rolling_window) ff_facs = np.round(ff_facs, 3) pyfig = px.line(ff_facs, title = 'Rolling FamaFrench factors ({}mo)'.format(rolling_window), ) layout = dict(plot_bgcolor = 'white', paper_bgcolor = 'white', legend = dict(bgcolor = 'white'), yaxis = dict(range = rng, title = 'Factor Value'), xaxis = dict(title = 'Date'), hovermode = 'x unified', height = height, width = width, shapes = [ { 'type' : 'line', 'xref' : 'paper', 'x0' : 0, 'y0' : 0, 'x1' : 1, 'y1' : 0, 'line' : { 'color': 'black', 'width': 1, 'dash': 'longdashdot' }, }, ] ) pyfig['layout'] = layout if not online: if plt_type == 'iplot': iplot(pyfig, show_link = False, ) elif plt_type == 'plot': plot(pyfig, show_link = False, filename = 'RollingFamaFrench.html') elif plt_type == 'show': pyfig.show(rendder = 'notebook_connceted') elif online: py.iplot(pyfig, width = width, height = height)
def scatter_matrix(df): df = df.sort_values(by="Churn", ascending=True) classes = df["Churn"].unique().tolist() classes class_code = {classes[k]: k for k in range(2)} class_code color_vals = [class_code[cl] for cl in df["Churn"]] color_vals pl_colorscale = "Viridis" pl_colorscale text = [df.loc[k, "Churn"] for k in range(len(df))] text trace = go.Splom( dimensions=[ dict(label="tenure", values=df["tenure"]), dict(label="MonthlyCharges", values=df["MonthlyCharges"]), dict(label="TotalCharges", values=df["TotalCharges"]), ], text=text, marker=dict( color=color_vals, colorscale=pl_colorscale, size=3, showscale=False, line=dict(width=0.1, color="rgb(230,230,230)"), ), ) axis = dict(showline=True, zeroline=False, gridcolor="#fff", ticklen=4) layout = go.Layout( dict( title="Scatter plot matrix for Numerical columns for customer attrition", autosize=False, height=800, width=800, dragmode="select", hovermode="closest", plot_bgcolor="rgba(240,240,240, 0.95)", xaxis1=dict(axis), yaxis1=dict(axis), xaxis2=dict(axis), yaxis2=dict(axis), xaxis3=dict(axis), yaxis3=dict(axis), ) ) data = [trace] fig = go.Figure(data=data, layout=layout) py.iplot(fig)
def dynamic_surf(dfs): """ """ for idx, df in enumerate(dfs): df = df.set_index('Unnamed: 0') data = [go.surface(z=np.array(dfs[0]))] layout = go.Layout(autosize=True, width=500, height=500, margin=dict(l=50, r=50, b=50, t=50)) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='test')
def plotly_3d(verts, faces): x, y, z = zip(*verts) print("Drawing") colormap = ['rgb(236, 236, 212)', 'rgb(236, 236, 212)'] fig = create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, backgroundcolor='rgb(64, 64, 64)', title="Interactive Visualization") iplot(fig)
def plot_pie(column): trace1 = go.Pie( values=churn[column].value_counts().values.tolist(), labels=churn[column].value_counts().keys().tolist(), hoverinfo="label+percent+name", domain=dict(x=[0, 0.48]), name="Churn Customers", marker=dict(line=dict(width=2, color="rgb(33, 75, 198)")), hole=0.6, ) trace2 = go.Pie( values=not_churn[column].value_counts().values.tolist(), labels=not_churn[column].value_counts().keys().tolist(), hoverinfo="label+percent+name", marker=dict(line=dict(width=2, color="rgb(33, 75, 99)")), domain=dict(x=[0.52, 1]), hole=0.6, name="Non Churn Customers", ) layout = go.Layout( dict( title=column + " distribution in customer attrition ", plot_bgcolor="rgb(243,243,243)", paper_bgcolor="rgb(243,243,243)", annotations=[ dict( text="churn customers", font=dict(size=13), showarrow=False, x=0.15, y=0.5, ), dict( text="Non Churn Customers", font=dict(size=13), showarrow=False, x=0.88, y=0.5, ), ], ) ) data = [trace1, trace2] fig = go.Figure(data=data, layout=layout) py.iplot(fig)
def exercise04(): ''' Data set: Iris Generate an overfitting / underfitting curve of kNN each of the testing and training accuracy performance scores series for a range of neighbor (k) values from 1 to 30 and plot the curves (number of neighbors is x-axis, performance score is y-axis on the chart). Return back the plotly url. ''' # ------ Place code below here \/ \/ \/ ------ #splits training and testing data X_train, X_test, y_train, y_test = tts(iris_df,iris_target,test_size = 0.2,random_state = 21, stratify = iris_target) #creates an array of neighbors from 1 to 30 neighbors = np.arange(1, 30) #creates empty lists to store train and test accuracy train_accuracy = np.empty(len(neighbors)) test_accuracy = np.empty(len(neighbors)) # Loop over different values of k for i, k in enumerate(neighbors): # Setup a k-NN Classifier with k neighbors: knn knn = KNN(n_neighbors = k) # Fit the classifier to the training data knn.fit(X_train,y_train) #Compute accuracy on the training set train_accuracy[i] = knn.score(X_train, y_train) #Compute accuracy on the testing set test_accuracy[i] = knn.score(X_test,y_test) #creates plotly figure object with neighbors as x and train and test accuracy as y fig = go.Figure(go.Scatter(x=neighbors, y=train_accuracy, mode='lines', name='Train Accuracy')) fig.add_trace(go.Scatter(x=neighbors, y =test_accuracy, mode = 'lines', name = 'Test Accuracy' )) #label figure fig.update_xaxes(title_text='Number of Neighbors') fig.update_yaxes(title_text='Accuracy') fig.update_layout(title = "Overfit Underfit Curve") #publishees the plot on plotly output = py.iplot(fig, filename='Overfit_Underfit_Curve') #fetches plot url from output plotly_overfit_underfit_curve_url = output.src # ------ Place code above here /\ /\ /\ ------ return plotly_overfit_underfit_curve_url
def compare_tracks(): c = get_db().cursor() trackids = request.form["tracks"] data = [] print("-------------------------") print(trackids) for i in trackids: c.execute(''' SELECT * FROM trackvars WHERE track_id=? ''',i) trackvars = [] dates = [] for o in c: trackvars.append(o[4]) dates.append(o[3]) trace = go.Scatter( x = dates, y = trackvars, mode = "lines+markers") data.append(trace) layout = go.Layout( title='Sammenligning af tracks', yaxis=dict( title='yaxis title' ), yaxis2=dict( title='yaxis2 title', titlefont=dict( color='rgb(148, 103, 189)' ), tickfont=dict( color='rgb(148, 103, 189)' ), overlaying='y', side='right' ) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig, filename='basic-line') return my_render("my_tracks_show.html")
def histogram(column): trace1 = go.Histogram( x=churn[column], histnorm="percent", name="Churn Customers", marker=dict(line=dict(width=0.5, color="black")), opacity=0.9, ) trace2 = go.Histogram( x=not_churn[column], histnorm="percent", name="Non Churn customers", marker=dict(line=dict(width=0.5, color="black")), opacity=0.9, ) data = [trace1, trace2] layout = go.Layout( dict( title=column + " distribution in customer attrition ", plot_bgcolor="rgb(243,243,243)", paper_bgcolor="rgb(243,243,243)", xaxis=dict( gridcolor="rgb(255, 255, 255)", title=column, zerolinewidth=1, ticklen=5, gridwidth=2, ), yaxis=dict( gridcolor="rgb(255, 255, 255)", title="percent", zerolinewidth=1, ticklen=5, gridwidth=2, ), ) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig)
def create3DPlot(path): depthChange = np.load(path) depthChange[depthChange!=depthChange] = 0 #interpolate dummy depthChange = np.array(Image.fromarray(depthChange).resize((224,224), resample= Image.BILINEAR)) depthChange *= 10 depthChange = depthChange.astype('int8') #see if you can use low precision float ''' analyzer: for line in depthChange: print(line) ''' data = [go.Surface(z=depthChange, colorscale='Viridis', cmax=40, cmin=-40)] layout = go.Layout( width=800, height=700, autosize=False, title='Depth Change', scene=dict( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)', range = [-40, 40] ), aspectratio = dict( x=1, y=1, z=0.7 ), aspectmode = 'manual' ) ) fig = dict(data=data, layout=layout) # IPython notebook # py.iplot(fig, filename='pandas-3d-surface', height=700, validate=False) url = py.iplot(fig, filename='3d-surface-depth-plot3') #This actually returns a IPython.lib.display.IFrame object return url
def plotCountries(self, countries, filename): titles = ["{} Logistic Curve".format(country) for country in countries] titles.insert(1, "Existing Cases vs. New Cases") fig = make_subplots( rows=3, cols=2, specs=[[{}, {"rowspan":3}], [{}, None], [{}, None]], subplot_titles=titles) for i, country in enumerate(countries): # print(i) self._addCountry(country, fig, i) fig.update_layout( title="Coronavirus in Countries: Confirmed Growth", xaxis_title="Log(Confirmed Cases)", yaxis_title="Log(Total New Cases in Last Week)", ) py.iplot(fig, filename = filename)
def draw_ape_boxplots_plotly(stats, upload_plots_online=False, show_figure=False): """ Simplified boxplot plotting using plotly for APE boxplots: See draw_ape_boxplots for the complicated version. Args: - stats: vio statistics (see 'draw_ape_boxplots' function) - upload_plots_online: if set to True it will publish plots online to plotly server. (to publish online, you need to follow the instructions here: ) If False, it will just show the boxplot figure. - show_figure: whether to display the figure or not Returns: - the handle to the plotly figure """ def listify_stats(stats): """ Makes a list of lists out of the stats (for easy conversion into pandas dataframe) """ stats_list = [] for dataset_name in stats: for pipeline in stats[dataset_name]: result = stats[dataset_name][pipeline] if result != False: result = result['absolute_errors'].np_arrays['error_array'] stats_list.append([dataset_name, pipeline, result]) return stats_list df = pd.DataFrame() log.info("Creating dataframe stats.") df = pd.DataFrame.from_records(listify_stats(stats)) df.columns = ['Dataset Name', 'Pipe Type', 'ATE errors'] figure = draw_boxplot_plotly(df) if upload_plots_online: py.iplot(figure, filename=figure.layout.title.text + '.html', world_readable=True, auto_open=False) if show_figure: figure.show() return figure
def plotGrowth(self): fig = go.Figure() self.state_dictLATEST = {} data = [] for region_name, region in self.regional_data.items(): for state, stateDF in region.groupby('state'): data.append(self._addState(state, stateDF, fig, region_name)) py.iplot(data, filename='states exponential growth') fig.update_layout( title="Coronavirus in States: Confirmed Growth", xaxis_title="Log(Confirmed Cases)", yaxis_title="Log(Total New Cases in Last Week)", ) fig.show() self.state_dfLATEST = pd.DataFrame(list( self.state_dictLATEST.values())) self.state_dfLATEST['state'] = self.state_dfLATEST['state'].apply( lambda x: us_state_abbrev[x])
def drawGanttChart(self): # Gantt Chart m_keys=[j+1 for j in range(self.__num_mc)] j_keys=[j for j in range(self.__num_job)] key_count={key:0 for key in j_keys} j_count={key:0 for key in j_keys} m_count={key:0 for key in m_keys} j_record={} for i in self.__sequence_best: gen_t=int(self.__pt[i][key_count[i]]) gen_m=int(self.__ms[i][key_count[i]]) j_count[i]=j_count[i]+gen_t m_count[gen_m]=m_count[gen_m]+gen_t if m_count[gen_m]<j_count[i]: m_count[gen_m]=j_count[i] elif m_count[gen_m]>j_count[i]: j_count[i]=m_count[gen_m] start_time=str(datetime.timedelta(seconds=j_count[i]-self.__pt[i][key_count[i]])) # convert seconds to hours, minutes and seconds end_time=str(datetime.timedelta(seconds=j_count[i])) j_record[(i,gen_m)]=[start_time,end_time] key_count[i]=key_count[i]+1 df=[] for m in m_keys: for j in j_keys: df.append(dict(Task='Machine %s'%(m), Start='2018-07-14 %s'%(str(j_record[(j,m)][0])), Finish='2018-07-14 %s'%(str(j_record[(j,m)][1])),Resource='Job %s'%(j+1))) fig = ff.create_gantt(df, index_col='Resource', show_colorbar=True, group_tasks=True, showgrid_x=True, title='Job shop Schedule') py.iplot(fig, filename='GA_job_shop_scheduling', world_readable=True, auto_open=True) #fig.show()
def __init__(self, df, r, c, today): self.df = df print('prepping df') self.prepDF() self.criteria_lst = [ 'sensitive_slopeBox_positive', 'sensitive_slopeBox_negative', 'sensitive_slopeBox_death', 'sensitive_slopeBox_hospitalizedCumulative' ] self.dates = self.df['date'].unique() self.states = self.df['state'].unique() print('initialzing the plot') fig = make_subplots(rows=r, cols=c, subplot_titles=('Positives', 'Negatives', 'Deaths', 'Hospitalizations'), specs=[[{ "type": "choropleth" }, { "type": "choropleth" }], [{ "type": "choropleth" }, { "type": "choropleth" }]]) self.Animate = AnimatedBase(fig) print('setting the initial state') self.Animate.fig.update_layout(geo_scope='usa') self.Animate.fig.update_layout(geo2_scope='usa') self.Animate.fig.update_layout(geo3_scope='usa') self.Animate.fig.update_layout(geo4_scope='usa') self.initialState() print('creating frames') self.createFrames() self.Animate.finalizeSliders() print('sending to the cloud') py.iplot(self.Animate.fig, filename="animated maps {}".format(today))
def plotHeatmap(array, name="plot"): data = Data([ Heatmap( z=array, colorscale='Greys' ) ]) layout = Layout( autosize=False, title=name ) fig = Figure(data=data, layout=layout) return py.iplot(fig, filename=name)
def monte_carlo(ticker1): response = requests.get( "https://head-stocks-java.herokuapp.com/api/stocks/predict/" + int(ticker1)) monteCarlo = pd.DataFrame() monteCarlo = response.json() sliced_arr = [] sliced_arr1 = [] sliced_arr2 = [] sliced_arr3 = [] sliced_arr4 = [] sliced_arr5 = [] sliced_arr6 = [] sliced_arr7 = [] sliced_arr8 = [] sliced_arr9 = [] sliced_arr = monteCarlo[0:9] sliced_arr1 = monteCarlo[10:19] sliced_arr2 = monteCarlo[20:29] sliced_arr3 = monteCarlo[30:39] sliced_arr4 = monteCarlo[40:49] sliced_arr5 = monteCarlo[50:59] sliced_arr6 = monteCarlo[60:69] sliced_arr7 = monteCarlo[70:79] sliced_arr8 = monteCarlo[80:89] sliced_arr9 = monteCarlo[90:99] fig = go.Figure() fig.add_trace(go.Scatter(y=sliced_arr, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr1, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr2, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr3, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr4, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr5, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr6, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr7, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr8, mode='lines+markers')) fig.add_trace(go.Scatter(y=sliced_arr9, mode='lines+markers')) fig.update_xaxes(showgrid=False, zeroline=False) fig.update_yaxes(showgrid=False, zeroline=False) fig.update_layout(showlegend=False) url = py.iplot(fig) print(url.src) return (url.src)
def exercise09(): ''' Load historical Bitcoin prices that are in JSON format from https://api.coindesk.com/v1/bpi/historical/close.json using start date 9/1/2017 and end date 10/5/2018. Documentation on the API is here: https://www.coindesk.com/api/ Note: You may need to use the requests library and header spoofing to grab the data and then giving it to a DataFrame With the prices loaded into the DataFrame: - Drop the disclaimer column - Remove the bottom two rows - Plot a price timeseries and publish it to Plotly using the Plotly API and set the URL to the chart to the plotly_url variable. Publication to Plotly will occur programmtically via plotly API. You will need to import the library and create an API key from the plotly dashboard. - Print the head - Print the tail ''' header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'} # ------ Place code below here \/ \/ \/ ------ #reads data directly from the api and specifies the start and end date #drops disclaimer column and removes last two rows df = pd.read_json("https://api.coindesk.com/v1/bpi/historical/close.json?start=2017-09-01&end=2018-10-05").drop(['disclaimer'], axis = 1)[:-2] #plots the bitcoin prices over time and specifies the axes and title labels fig = go.Figure(go.Scatter(x=df.index, y=df.bpi, mode='lines', name='Bitcoin Prices over Time')) fig.update_xaxes(title_text='Date') fig.update_yaxes(title_text='Price') fig.update_layout(title = "Bitcoin Prices Over Time") #publishees the plot on plotly output = py.iplot(fig, filename='Bitcoin_Prices') #fetches plot url from output plotly_url = output.src #prints head and tail of dataframe print(df.head(n=5)) print(df.tail(n=5)) # ------ Place code above here /\ /\ /\ ------ return df, plotly_url
def areaplot(alpha): color = random_color() trace0 = go.Scatter( x=pred2.conf_int(alpha=alpha).index, y=pred2.conf_int(alpha=alpha).iloc[:,1], fill= None, mode='lines', showlegend=False, name='Upper Bound', line=dict(width=0.5, color='rgba({},{},{},{})'.format(color[0],color[1],color[2],0.5) )) trace1 = go.Scatter( x=pred2.conf_int(alpha=alpha).index, y= pred2.conf_int(alpha=alpha).iloc[:,0], fill='tonexty', mode='lines', line=dict(width=0.5, color='rgba({},{},{},{})'.format(color[0],color[1],color[2],0.5)), name = 'alpha = {}'.format(alpha) ) trace2 = go.Scatter( x=valid.index, # assign x as the dataframe column 'x' y=valid, name = 'Real data', line=dict(color='rgb{}'.format(color)), mode='lines') trace3 = go.Scatter( x = hightlight(alpha).anomly_date, y = hightlight(alpha).anomly_y, name = 'Alert points', hoverinfo='none', mode = 'markers' ) Data = [trace0, trace1, trace2, trace3] return py.iplot(Data, filename= 'Area Plot for different alfa')
def plotly_plot(xs, ys, n_class, cmap_name='viridis', title='', filename='temp'): # color amp viridis_cmap = mlt.cm.get_cmap('viridis') norm = mlt.colors.Normalize(vmin=0, vmax=n_class) # 컬러맵의 구간을 나눔 viridis_rgb = [ mlt.colors.colorConverter.to_rgb(viridis_cmap(norm(i))) for i in range(0, n_class) ] # 컬러맵을 RGB컬러로 변환 viridis_rgb_dict = dict(zip(list(range(3)), viridis_rgb)) # 각 컬러를 숫자로 키값 만듬 label_color = np.vectorize(lambda x: 'rgb' + str(viridis_rgb_dict[x]))( ys) # rgb(컬러) 와 같이 만듬 # 각 점의 텍스트 만들기 text_list = [str(x) + '_' + str(ys[x]) for x in list(range(xs.shape[0]))] data = [ go.Scatter(x=xs[:, 0], y=xs[:, 1], mode='markers', marker=dict(size=15, color=label_color), text=text_list) ] layout = go.Layout(title=title, xaxis={'title': 'x1'}, yaxis={'title': 'x2'}) fig = go.Figure(data=data) return py.iplot(fig, filename=filename)
def plotChoropleth(self): fig = px.choropleth( locations=self.state_dfLATEST['state'], locationmode="USA-states", title="States By Normalized Total Cases (Total)", color=self.state_dfLATEST['normalized total cases'], scope="usa") py.iplot(fig, filename="states by normalized total cases") fig = px.choropleth( locations=self.state_dfLATEST['state'], locationmode="USA-states", title="States By Normalized New Cases (Last Week)", color=self.state_dfLATEST['normalized new cases last week'], scope="usa") py.iplot(fig, filename="states by normalized new cases last week") fig = px.choropleth(locations=self.state_dfLATEST['state'], locationmode="USA-states", title="States By Normalized New Cases (Last Day)", color=self.state_dfLATEST['normalized new cases'], scope="usa") py.iplot(fig, filename="states by normalized new cases last day")
def assets_Liabilities1(ticker): currentAssets = [] receivables = [] ppe = [] totalassets = [] currentliabilities = [] longTerm = [] noncurrent = [] equity = [] indices = pd.DataFrame( list(collection.find({"ticker_name": ticker}, {"ticker_dates"}))) for val in indices['ticker_dates'][0]: if ('Current Assets' in val): currentAssets.append(val['Current Assets']) if ('Receivables' in val): receivables.append(val['Receivables']) if ('Net PP&E' in val): ppe.append(val['Net PP&E']) if ('Total Assets' in val): totalassets.append(val['Total Assets']) if ('Current Liabilities' in val): currentliabilities.append(val['Current Liabilities']) if ('Long Term Debt' in val): longTerm.append(val['Long Term Debt']) if ('Total Noncurrent Liabilities' in val): noncurrent.append(val['Total Noncurrent Liabilities']) if ('Total Equity' in val): equity.append(val['Total Equity']) otherlongterm = noncurrent[-1] - longTerm[-1] longassets = totalassets[-1] - currentAssets[-1] - ppe[-1] - receivables[-1] labels = ['Current Assets', 'Net PP&E', 'Receiavbles', 'Long Term Assets'] values = [currentAssets[-1], ppe[-1], receivables[-1], longassets] labels1 = [ 'Current Liabilities', 'long term debt', 'Total Noncurrent Liabilities', 'Other Long Term Liabilities', 'Total Equity' ] values1 = [ currentliabilities[-1], longTerm[-1], noncurrent[-1], otherlongterm, equity[-1] ] # Create subplots: use 'domain' type for Pie subplot fig = make_subplots(rows=1, cols=2, specs=[[{ 'type': 'domain' }, { 'type': 'domain' }]]) fig.add_trace(go.Pie(labels=labels, values=values, name=""), 1, 1) fig.add_trace(go.Pie(labels=labels1, values=values1, name=""), 1, 2) fig.update_traces(hole=.5, hoverinfo="label+percent+name") fig.update_layout(showlegend=False, title_text=ticker + "Assets to Liabilities", annotations=[ dict(text='Total Assets', x=0.18, y=0.5, font_size=12, showarrow=False), dict(text='Total Liabilities', x=0.85, y=0.5, font_size=12, showarrow=False) ]) url = py.iplot(fig) print(url.src) return (url.src)
def ohlc_indices(ticker_id): print(ticker_id) # Fetching the indices name and projecting ticker_dates indices = pd.DataFrame( list(collection.find({"ticker_id": int(ticker_id)}, {"ticker_dates"}))) dates = [] open = [] high = [] low = [] close = [] volume = [] # Looping through the result to fetch the dates and their corresponding values for val in indices['ticker_dates'][0]: dates.append(val['date']) open.append(val["opening"]) high.append(val["high"]) low.append(val["low"]) close.append(val["closing"]) volume.append(val["volume"]) # Creating a new DataFrame containing required data indexDate = pd.DataFrame({ "date": dates, "open": open, "close": close, "low": low, "high": high, "volume": volume }) # Plotting the graph with Rnage Slector and Range SLider layout = dict(yaxis=dict(showgrid=False, title="Prices", showline=True, linewidth=1, linecolor='#cacaca'), xaxis=dict(rangeselector=dict(buttons=list([ dict(count=1, label="1m", step="month", stepmode="backward"), dict(count=6, label="6m", step="month", stepmode="backward"), dict(count=1, label="YTD", step="year", stepmode="todate"), dict(count=1, label="1y", step="year", stepmode="backward"), dict(step="all") ]), activecolor="#39abf7", x=0.11, xanchor="left", y=1.1, yanchor="top"), rangeslider=dict(visible=True), type='date', showgrid=False, title="Date", showline=True, linewidth=1, linecolor='#cacaca'), paper_bgcolor='#fafafa', plot_bgcolor='#fafafa') fig = go.Figure(data=go.Ohlc(x=indexDate['date'], open=indexDate['open'], high=indexDate['high'], low=indexDate['low'], close=indexDate['close']), layout=layout) url = py.iplot(fig) print(url.src) return (url.src)
def compnay_indices(ticker_name): companyohlc = pd.DataFrame( list(collection.find({"ticker_name": ticker_name}, {"ohlc_dates"}))) companydates = [] companyopen = [] companyhigh = [] companylow = [] companyclose = [] companyvolume = [] companydata = [] for val in companyohlc['ohlc_dates'][0]: companydates.append(val['date']) if ('opening' in val): companyopen.append(val["opening"]) else: companyopen.append('-') if ('high' in val): companyhigh.append(val["high"]) else: companyhigh.append('-') if ('low' in val): companylow.append(val["low"]) else: companylow.append('-') if ('closing' in val): companyclose.append(val["closing"]) else: companyclose.append('-') if ('volume' in val): companyvolume.append(val["volume"]) else: companyvolume.append('-') companyDate = pd.DataFrame({ "date": companydates, "open": companyopen, "close": companyclose, "low": companylow, "high": companyhigh, "volume": companyvolume }) layout = dict( title='Stock Chart', yaxis=dict(showgrid=False, title="Prices"), xaxis=dict(rangeselector=dict(buttons=list([ dict(count=1, label="1m", step="month", stepmode="backward"), dict(count=6, label="6m", step="month", stepmode="backward"), dict(count=1, label="YTD", step="year", stepmode="todate"), dict(count=1, label="1y", step="year", stepmode="backward"), dict(step="all") ])), rangeslider=dict(visible=True), type='date', showgrid=False, title="Date")) fig = go.Figure(data=go.Ohlc(x=companyDate['date'], open=companyDate['open'], high=companyDate['high'], low=companyDate['low'], close=companyDate['close']), layout=layout) url = py.iplot(fig) print(url.src) return (url.src)
def stock_chart(ticker1, ticker2): company = pd.DataFrame( list(collection.find({"ticker_id": int(ticker1)}, {"ticker_dates"}))) company1 = pd.DataFrame( list(collection.find({"ticker_name": ticker2}, {"ticker_dates"}))) stockDate = [] stockDate1 = [] stockPrice = [] stockPrice1 = [] # Looping through result to fetch dates and get their repective values for val in company['ticker_dates'][0]: stockDate.append(val['date']) # Append the value of Share Price if present , otherwise append '-' if ('Share Price' in val): stockPrice.append(val['Share Price']) else: stockPrice.append("-") for val in company1['ticker_dates'][0]: stockDate1.append(val['date']) # Append the value of Share Price if present , otherwise append '-' if ('Share Price' in val): stockPrice1.append(val['Share Price']) else: stockPrice1.append("-") # Appending into final dataframe to plot the graph sharePrice = pd.DataFrame({"date": stockDate, "sharePrice": stockPrice}) sharePrice1 = pd.DataFrame({ "date": stockDate1, "sharePrice1": stockPrice1 }) trace2 = go.Scatter(x=sharePrice['date'], y=sharePrice['sharePrice'], text='Share Price', marker=dict(size=2, color='#ff4d4d'), name=ticker1) trace1 = go.Scatter(x=sharePrice1['date'], y=sharePrice1['sharePrice1'], text='Share Price', marker=dict(size=2, color='#27ae60'), name=ticker2) layout = dict(title='Stock Chart', xaxis=dict(showgrid=False, title="Date", rangeselector=dict(buttons=list([ dict(count=1, label="1d", step="day", stepmode="backward"), dict(count=7, label="1w", step="day", stepmode="backward"), dict(count=1, label="1m", step="month", stepmode="backward"), dict(count=3, label="3m", step="month", stepmode="backward"), dict(count=6, label="6m", step="month", stepmode="backward"), dict(count=1, label="YTD", step="year", stepmode="todate"), dict(count=1, label="1y", step="year", stepmode="backward"), dict(count=5, label="5y", step="year", stepmode="backward"), dict(step="all") ]), activecolor="#ff6e85", x=0.11, xanchor="left", y=1.1, yanchor="top"), showline=True, linewidth=1, linecolor='#707070'), yaxis=dict(showgrid=False, title="Share Price", showline=True, linewidth=2, linecolor='#707070'), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)') data = [trace2, trace1] fig = dict(data=data, layout=layout) url = py.iplot(fig) print(url.src) return (url.src)
# # Scatter Plots sencillos # In[10]: N = 2000 random_x = np.random.randn(N) random_y = np.random.randn(N) # In[11]: trace = go.Scatter(x=random_x, y=random_y, mode="markers") # In[12]: py.iplot([trace], filename="basic-scatter") # In[13]: plot_url = py.plot([trace], filename="basic-scatter-inline") plot_url # # Gráficos combinados # # In[14]: N = 200 rand_x = np.linspace(0, 1, N) rand_y0 = np.random.randn(N) + 3 rand_y1 = np.random.randn(N)
mode = "gauge+number", title = {'text':"<b> RECIFE </b><br><span style='color: gray;font-size:0.8em'> % População com 1ª dose da vacina do Covid-19</span>", 'font': {"size": 20}}, gauge = {'axis': {'range': [None, 100]}, 'bar': {'color': 'white'}, 'steps' : [ {'range': [0, 20], 'color': "#F2726F"}, {'range': [20, 50], 'color': "#fcff33"}, {'range': [50, 70], 'color': "#FFC533"}, {'range': [70, 100], 'color': "#89D958"}], 'threshold' : {'line': {'color': "black", 'width': 4}, 'thickness': 0.75, 'value': 80}})) fig1a.add_annotation(text= f"{dose_data} <br> Baseada na população do Recife de 1,653,461 habitantes <br> Repositório - https://github.com/silpai/Covid-19-Analysis<br> Dados: github.com/wcota/covid19br | conectarecife.recife.pe.gov.br/vacinometro <br>", xref="paper", yref="paper", x=0.50, y=-0.25, showarrow=False) py.iplot(fig1a,filename="Recife-1aDose-Vacina-Covid19") # to show in jupter #Speedometro 2a dose fig2a = go.Figure(go.Indicator( domain = {'x': [0, 1], 'y': [0, 1]}, value = float(dos['perct_2aDose_Unica'].tail(1)), number = {'suffix': "%"}, mode = "gauge+number", title = {'text':"<b> RECIFE </b><br><span style='color: gray;font-size:0.8em'> % População com 2ª dose ou dose única da vacina do Covid-19</span>", 'font': {"size": 20}}, gauge = {'axis': {'range': [None, 100]}, 'bar': {'color': 'white'}, 'steps' : [ {'range': [0, 20], 'color': "#F2726F"}, {'range': [20, 50], 'color': "#fcff33"}, {'range': [50, 70], 'color': "#FFC533"}, {'range': [70, 100], 'color': "#89D958"}],