def box_plot(y_positive, y_negative, y_neutral, name): '''plot box plot takes in list of y variables that we want to plot''' fig = go.Figure() fig.add_trace(go.Box(y=y_positive, name='positive' )) fig.add_trace(go.Box(y=y_negative, name='Negative' )) fig.add_trace(go.Box(y=y_neutral, name='Neutral' )) fig.update_layout( title={ 'text': f"BoxPlot of sentiments of {name}", 'y': 0.99, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top', 'font': dict( family='Rockwell', color='dim gray', size=30), }, #template='plotly_dark', xaxis=dict( showgrid=False ), yaxis=dict( showgrid=False )) return(offl.plot(fig, show_link=False, output_type="div", include_plotlyjs=False))
def get_figure1(df): fig = go.Figure() fig.add_trace( go.Box(x=df['sodium_dv'].dropna() * 100, name='Sodium', boxmean=True)) fig.add_trace( go.Box(x=df['totalfat_dv'].dropna() * 100, name='Total Fat', boxmean=True)) fig.add_trace( go.Box(x=df['sugar'].dropna(), name='Sugar', boxmean=True)) fig.update_layout(barmode='stack') fig.update_traces(opacity=0.75) fig['layout']['xaxis'].update(range=[0, 100]) fig.update_layout( xaxis_title="Daily Value (%)", margin=dict( l=0, r=0, b=50, t=50, ), title={ 'text': 'Distribution of Select Nutrients (Stores Combined)', 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top' }, height=400) return to_html(fig, include_plotlyjs=False, full_html=False)
def addBox(self, column): if self.orientation == 'V': self.fig.add_trace(go.Box(y=column)) elif self.orientation == 'H': self.fig.add_trace(go.Box(x=column)) else: self.fig.add_trace(go.Box(y=column))
def figure_box_hist(df, group, linear, bar): """ Update box plot and histogram in comparison tab depending on drop downs """ df_linear = df[df['type'] == linear] df_bar = df[df['type'] == bar] name = df[group].unique() colors = px.colors.qualitative.Plotly fig_histogram = make_subplots(rows=1, cols=2, subplot_titles=(linear, bar)) fig_box_plot = make_subplots(rows=1, cols=2, subplot_titles=(linear, bar)) for name, i in enumerate(name): df_l = df_linear[df_linear[group] == i] df_b = df_bar[df_bar[group] == i] i = str(i) fig_histogram.add_trace(go.Histogram(x=df_l['Value'], name=i, showlegend=False, legendgroup=i, marker_color=colors[name]), row=1, col=1) fig_histogram.add_trace(go.Histogram(x=df_b['Value'], name=i, legendgroup=i, marker_color=colors[name]), row=1, col=2) fig_box_plot.add_trace(go.Box(y=df_l['Value'],name=i, showlegend=False, legendgroup=i, marker_color=colors[name]), row=1, col=1) fig_box_plot.add_trace(go.Box(y=df_b['Value'], name=i, legendgroup=i, marker_color=colors[name]), row=1, col=2) # Overlay both histograms fig_histogram.update_layout(barmode='stack') fig_histogram.update_layout(template='plotly_white') fig_box_plot.update_layout(template='plotly_white') return fig_box_plot, fig_histogram
def plot_weather(process_dict): #plotting #boxplot fig1a = go.Figure() fig1a.add_trace(go.Box(y=process_dict['overallTs'], name="Temperature")) fig1a.add_trace( go.Box(y=process_dict['overallRFTs'], name="Real Feel Temperature")) fig1a.update_layout( title= f"Boxplot comparison of Temperature and Real Feel Temperature on {process_dict['Date']} for the past {process_dict['File']}", xaxis_title='Variable', yaxis_title='Temperature (°C)') fig1a.show() #bar graph fig1b = go.Figure() fig1b.add_trace( go.Bar(x=process_dict['WeatherText'], y=process_dict['WeatherFreq'], name="Weather")) fig1b.update_layout( title= f"Frequency comparison of WeatherText on {process_dict['Date']} for the past {process_dict['File']}", xaxis_title='WeatherText Category', yaxis_title='Count') fig1b.show()
def boxplot_through_the_day(plot_df): """Returns a plot with the boxplot of the estimations through the day""" fig = go.Figure() fig.add_trace( go.Box( x=plot_df['departure_time'].dt.hour, y=plot_df['trip_time_estimate'].dt.total_seconds() / 60, name='running time estimate', marker=dict(color='red', ), )) fig.add_trace( go.Box( x=plot_df['departure_time'].dt.hour, y=plot_df['trip_time'].dt.total_seconds() / 60, name='running time', marker=dict(color='green', ), )) #Edit the layout fig.update_layout( title='Estimated running times and running times through the day', xaxis_title='Hour of the day', yaxis_title='Running time (minutes)') return fig
def get_boxplots(df, ts_df): df_copy = df.copy() ts_df_copy = ts_df.copy() df_copy["text"] = df["id"].astype(str) + " si(" + df["si"].astype(str) + "), length(" + df["length"].astype(str) \ + "), area(" + df["area"].astype(str) + ")" ts_df_copy["text"] = ts_df["id"].astype(str) + " si(" + ts_df["si"].astype(str) \ + "), length(" + ts_df["length"].astype(str) + "), area(" + ts_df["area"].astype(str) + ")" fig = make_subplots(rows=1, cols=5) fig.add_trace(go.Box(y=list(df_copy["si"]), name="si (event)", text=df_copy["text"]), row=1, col=1) fig.add_trace(go.Box(y=list(ts_df_copy["si"]), name="si (timeseries)", text=ts_df_copy["text"]), row=1, col=2) fig.add_trace(go.Box(y=list(df_copy["length"]), name="length", text=df_copy["text"]), row=1, col=3) fig.add_trace(go.Box(y=list(df_copy["area"]), name="area", text=df_copy["text"]), row=1, col=4) fig.add_trace(go.Box(y=list(ts_df_copy["meanPre"]), name="meanPre", text=ts_df_copy["text"]), row=1, col=5) return fig
def visualize_age_relations(dbutils): dataframe_pd = load_dataset(sys.argv[1], "age_relations", dbutils) display_positive = dataframe_pd["positive"] display_negative = dataframe_pd["negative"] display_age = dataframe_pd["age"] rec_age_fig = make_subplots( rows=1, cols=2, subplot_titles=("Positive test/age coefficient correlation", "Negative test/age coefficient correlation")) rec_age_fig.add_trace(go.Box(x=display_positive, y=display_age, name="Positive", marker_color=color_scheme.color_300), row=1, col=1) rec_age_fig.add_trace(go.Box(x=display_negative, y=display_age, name="Negative", marker_color=color_scheme.color_700), row=1, col=2) rec_age_fig.update_traces(boxpoints='all') rec_age_fig.update_layout( title_text="Subplots of age in relation a positive/negative test result" ) rec_age_fig.show() return None
def box_wp(): layout = dict(title="", template="plotly_white", showlegend=False) fig = go.Figure(layout=layout) # whole pancreas protein try: wpp_wt = [ whole_pancreas_pro_wt_1, whole_pancreas_pro_wt_2, whole_pancreas_pro_wt_3, whole_pancreas_pro_wt_4 ] wpp_g12d = [ whole_pancreas_pro_g12d_1, whole_pancreas_pro_g12d_2, whole_pancreas_pro_g12d_3 ] fig.add_trace( go.Box(x=['WT', 'WT', 'WT', 'WT'], y=wpp_wt, name='WT', marker_color='lightseagreen', boxpoints='all', pointpos=0)) fig.add_trace( go.Box(x=['G12D', 'G12D', 'G12D'], y=wpp_g12d, name='G12D', marker_color='lightseagreen', boxpoints='all', pointpos=0)) except: fig.add_trace(go.Box(y=[], name='Whole pancreas WT')) fig.add_trace(go.Box(y=[], name='Whole pancreas G12D')) fig.update_layout(xaxis={'title': 'Whole pancreas'}, yaxis={'title': None}) plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div
def box_ce(): layout = dict(title="", template="plotly_white", showlegend=False) fig = go.Figure(layout=layout) # scraped colon protein try: scp_wt = [ scraped_colon_pro_fabp_1, scraped_colon_pro_fabp_2, scraped_colon_pro_fabp_4, scraped_colon_pro_fabp_5 ] scp_g12d = [ scraped_colon_pro_g12d_1, scraped_colon_pro_g12d_2, scraped_colon_pro_g12d_3, scraped_colon_pro_g12d_4 ] fig.add_trace( go.Box(x=['WT', 'WT', 'WT', 'WT'], y=scp_wt, name='WT', marker_color='#636EFA', boxpoints='all', pointpos=0)) fig.add_trace( go.Box(x=['G12D', 'G12D', 'G12D', 'G12D'], y=scp_g12d, name='G12D', marker_color='#636EFA', boxpoints='all', pointpos=0)) except: fig.add_trace(go.Box(y=[], name='Colonic epithelium WT')) fig.add_trace(go.Box(y=[], name='Colonic epithelium G12D')) fig.update_layout(xaxis={'title': 'Colonic epithelium'}, yaxis={'title': None}) plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div
def plotBoxPDF(listOfDictonaries, opFile): pathToDir, opFileName = os.path.split(opFile) # First check if the path entered by the user is correct or not. if os.path.exists(os.path.abspath(pathToDir)): pathToOutputDir = os.path.join(os.path.abspath(pathToDir), opFileName) # Store the output file name and use it in the with open loop fileName = str(pathToOutputDir) + ".pdf" fig = go.Figure() for i in listOfDictonaries: y_axis = i['tmpMed'] hopName = "Hop " + str(i['hop']) check_flag = i['avg'] if check_flag != 0: fig.add_trace(go.Box(y=y_axis, name=hopName)) fig.write_image(fileName) print("Program excuted successfully and file is stored at:", fileName) else: print("The path entered is not a valid path:", pathToDir) print("Creating the output file at:", os.getcwd()) fileName = opFileName + ".pdf" fig = go.Figure() for i in listOfDictonaries: y_axis = i['tmpMed'] hopName = "Hop " + str(i['hop']) check_flag = i['avg'] if check_flag != 0: fig.add_trace(go.Box(y=y_axis, name=hopName)) fig.write_image(fileName)
def BoxPlotCoEvolvedFiles(co_evolved, not_co_evolved): fig = go.Figure() fig.add_trace( go.Box(y=co_evolved, name="Co-Evolved Files", marker_color="cornflowerblue")) fig.add_trace( go.Box(y=not_co_evolved, name="Not Co-Evolved Files", marker_color="crimson")) fig.update_layout( width=900, height=550, yaxis_title='Distribution of Co-Evolved Files in Commits', # legend=dict( # yanchor="top", # y=0.99, # xanchor="right", # x=0.99 # ) showlegend=False) fig.show()
def grouped_box_plot(data, cat_col, num_cols, title=None, y_title=None, x_title=None, points=True): """ Create a box plot for a continous variable grouped by a categorical variable :param data: :type data: :param cat_col: :type cat_col: :param num_col: :type num_col: :return: :rtype: """ groups = data.groupby(cat_col) fig = go.Figure() for variable in num_cols: trace_x = [] trace_y = [] for idx, group in groups: y = list(group[variable][group[variable].notnull()]) x = [idx for i in range(len(y))] trace_y += y trace_x += x # Wrap the plot titles if len(variable) > 30: display_var = "<br>".join(textwrap.wrap(variable, width=30)) else: display_var = variable if points: fig.add_trace( go.Box(y=trace_y, x=trace_x, name=display_var, boxpoints='all', jitter=0.2)) else: fig.add_trace(go.Box(y=trace_y, x=trace_x, name=display_var)) fig.update_layout(title=title, title_x=0.5, yaxis_title=y_title, xaxis_title=cat_col, boxmode='group', width=1000) if x_title: fig.update_layout(xaxis_title=x_title, ) legend = dict(yanchor="top", y=0.99, x=1.02) fig.update_layout(legend=legend) fig.write_image("grouped_box_plot.png") fig.show()
def main(dataframe_files): """ :param dataframe_files: :return: """ df = pd.concat((pd.read_csv(f) for f in dataframe_files)) for sample_id in sorted(df['Sample'].unique()): fig = go.Figure() for assembler in sorted(df['Assembler'].unique()): contigs = df['Contig Len'][df['Assembler'] == assembler] mapped_contigs = df['Contig Len'][(df['Mapped'] != 'Unmapped') & (df['Assembler'] == assembler)] print(','.join([ assembler, f'{len(mapped_contigs)} ({(len(mapped_contigs) / len(contigs)) * 100:.2f}%)', f'{sum(mapped_contigs)} ({(sum(mapped_contigs) / sum(contigs)) * 100:.2f}%)' ])) # mapped contigs as boxplots fig.add_trace( go.Box(x=df['Contig Len'][(df['Mapped'] != 'Unmapped') & (df['Assembler'] == assembler)], name=assembler, boxpoints='outliers', boxmean=False, fillcolor='#D3D3D3', line=dict(color='#000000'))) # unmapped contigs as scatter-like plot (boxplot showing only the underlying data) fig.add_trace( go.Box(x=df['Contig Len'][(df['Mapped'] == 'Unmapped') & (df['Assembler'] == assembler)], name=assembler, boxpoints='all', pointpos=0, marker=dict(color='rgba(178,37,34,0.7)'), line=dict(color='rgba(0,0,0,0)'), fillcolor='rgba(0,0,0,0)')) fig.update_layout( showlegend=False, xaxis_type="log", xaxis_title="Contig size (Log bp)", title= "Contig size distribution per assembler (contigs over 1000 bp)", plot_bgcolor='rgb(255,255,255)', xaxis=dict(zeroline=False, gridcolor='#DCDCDC')) plot(fig, filename='{}_contig_size_distribution.html'.format(sample_id), auto_open=False) fig.write_json( file='{}_contig_size_distribution.json'.format(sample_id))
def update_tumor_volume(input_): traces = [] print(input_) if input_ is None: drug_name = 'Placebo' traces.append( go.Box(x=merged_df[merged_df['Drug Regimen'] == drug_name]['Timepoint'], y=merged_df[merged_df['Drug Regimen'] == drug_name] ['Tumor Volume (mm3)'], marker_color=drug_colors[drug_name], name=drug_name)) else: # drug_list = input_['points'][1]['Drug Regimen'] drug_list = [] for drug_name in drug_list: traces.append( go.Box(x=merged_df[merged_df['Drug Regimen'] == drug_name]['Timepoint'], y=merged_df[merged_df['Drug Regimen'] == drug_name] ['Tumor Volume (mm3)'], marker_color=drug_colors[drug_name], name=drug_name, customdata=[drug_name])) return { 'data': traces, 'layout': dict(xaxis={ 'title': 'time point', }, yaxis={ 'title': 'tumor volume mm3', 'range': [ merged_df['Tumor Volume (mm3)'].min(), merged_df['Tumor Volume (mm3)'].max() ], 'showgrid': False }, boxmode='group', autosize=False, paper_bgcolor=colors['chart-background'], plot_bgcolor=colors['chart-background'], margin={ 'l': 40, 'b': 40, 't': 10, 'r': 10 }, legend={ 'x': 0.99, 'y': 1 }, clickmode='event+select') }
def makestatsGraph(date=None): fig = go.Figure() tmp = df2[df2.Date == df2.Date.max()].copy() fig.add_trace(go.Box(y=np.log(tmp.Mort), name="Mortality")) fig.add_trace(go.Box(y=np.log(tmp.DP100K + 1), name="Deaths per 100K")) fig.add_trace(go.Box(y=np.log(tmp.CP100K + 1), name="Cases per 100K")) fig.update_layout(title="Box Plots", title_x=0.5, yaxis=dict(title="Logarithmic scale")) return fig
def C(selectinfo, checkinfo): traces = [] drug_list = [] if selectinfo: for drug in selectinfo['points']: if drug['customdata'][0] not in drug_list: drug_list.append(drug['customdata'][0]) if drug_list: for drug_name in drug_list: df_box = mdf[mdf['Drug Regimen'] == drug_name] traces.append( go.Box( x=df_box['Timepoint'], y=df_box['Tumor Volume (mm3)'], opacity=0.6, name=drug_name, marker=dict(color=drug_colors[drug_name]), )) else: for drug_name in checkinfo: df_box = mdf[mdf['Drug Regimen'] == drug_name] traces.append( go.Box( x=df_box['Timepoint'], y=df_box['Tumor Volume (mm3)'], opacity=0.6, name=drug_name, marker=dict(color=drug_colors[drug_name]), )) return { 'data': traces, 'layout': dict(boxmode="group", xaxis={'title': 'timepoint'}, yaxis={ 'title': 'tumor Volume (mm3)', 'showgrid': False }, autosize=False, paper_bgcolor=colors['chart-background'], plot_bgcolor=colors['chart-background'], margin={ 'l': 40, 'b': 40, 't': 10, 'r': 10 }, showlegend=True, legend_traceorder="reversed", legend={ 'x': 1, 'y': 1 }) }
def box_plot(): np.random.seed(1) y0 = np.random.randn(50) - 1 y1 = np.random.randn(50) + 1 fig = go.Figure() fig.add_trace(go.Box(y=y0)) fig.add_trace(go.Box(y=y1)) fig.update_layout(title='Box Plot') plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div
def buildgraph_ex3(data1, data2): fig1 = go.Figure() fig1.add_trace( go.Scatter(mode='markers', x=data1, marker=dict(color='Blue'))) fig1.add_trace( go.Scatter(mode='markers', x=data2, marker=dict(color='Red'))) fig1.add_shape(type="line", x0=np.mean(data1), y0=1, x1=np.mean(data1), y1=100, line=dict(color="Blue", width=4, dash="dashdot")) fig1.add_shape(type="line", x0=np.mean(data2), y0=1, x1=np.mean(data2), y1=100, line=dict(color="Red", width=4, dash="dashdot")) fig1.update_layout(barmode='overlay') fig1.update_layout(xaxis_range=[-10, 10]) fig1.update_traces(opacity=0.7) fig1.layout.update(showlegend=False) fig1.update_layout(title_text='Scatter Plot') graph1 = dcc.Graph(figure=fig1) fig2 = go.Figure() fig2.add_trace(go.Histogram(x=data1, name='Group 1')) fig2.add_trace(go.Histogram(x=data2, name='Group 2')) fig2.update_layout(barmode='overlay') fig2.update_traces(opacity=0.7) fig2.update_layout(title_text='Histogram') graph2 = dcc.Graph(figure=fig2) fig3 = go.Figure() fig3.add_trace(go.Box(y=data1, name='Group 1')) fig3.add_trace(go.Box(y=data2, name='Group 2')) fig3.update_layout(title_text='Boxplot') graph3 = dcc.Graph(figure=fig3) mult = sc.t.ppf((1 + 0.95) / 2, len(data1) - 1) fig4 = go.Figure() fig4.add_trace( go.Bar(name='Control', x=['Group 1', 'Group 2'], y=[np.mean(data1), np.mean(data2)], error_y=dict(type='data', array=[sc.sem(data1) * mult, sc.sem(data2) * mult]))) fig4.update_layout(title_text='Bargraph with Errorbars') graph4 = dcc.Graph(figure=fig4) return graph1, graph2, graph3, graph4
def get_log_residual_plot(): #meta_pre = ['meta_pre_g1', 'meta_pre_g2', 'meta_pre_g3', 'meta_pre_g4', 'meta_pre_g5', 'meta_pre_g6', 'meta_pre_g7', 'meta_pre_g8'] #video_pre = ['video_pre_g1', 'video_pre_g2', 'video_pre_g3', 'video_pre_g4', 'video_pre_g5', 'video_pre_g6', 'video_pre_g7', 'video_pre_g8'] current_dir = os.path.dirname(os.path.realpath(__file__)) data_file = os.path.join(current_dir, 'data', 'summary_final_result.csv') #csv = np.genfromtxt(data_file, delimiter=None, comments='#') g8_result_final = pd.read_csv(data_file) meta_res_log = [ 'meta_res_log_g1', 'meta_res_log_g2', 'meta_res_log_g3', 'meta_res_log_g4', 'meta_res_log_g5', 'meta_res_log_g6', 'meta_res_log_g7', 'meta_res_log_g8' ] video_res_log = [ 'video_res_log_g1', 'video_res_log_g2', 'video_log_res_g3', 'video_res_log_g4', 'video_res_log_g5', 'video_res_log_g6', 'video_res_log_g7', 'video_res_log_g8' ] #g8_result_final = pd.read_csv('summary_final_result.csv') N = 8 c = ['hsl(' + str(h) + ',50%' + ',50%)' for h in np.linspace(0, 360, N)] d = ['hsl(' + str(h) + ',30%' + ',30%)' for h in np.linspace(0, 360, N)] group = [ 'Group1', 'Group2', 'Group3', 'Group4', 'Group5', 'Group6', 'Group7', 'Group8' ] fig = go.Figure() for i in range(int(N)): fig.add_trace( go.Box(x=g8_result_final[meta_res_log[i]], y=[group[i]] * len(g8_result_final[meta_res_log[i]]), name='Logarithm of meta residuals of Group ' '{}'.format(i + 1), marker_color=c[i])) fig.add_trace( go.Box(x=g8_result_final[video_res_log[i]], y=[group[i]] * len(g8_result_final[video_res_log[i]]), name='Logarithm of video residuals of Group ' '{}'.format(i + 1), marker_color=d[i])) fig.update_layout(xaxis=dict(title='The absolute logarithm of residuals', zeroline=False), boxmode='group') fig.update_traces(orientation='h') # horizontal box plots #fig.show() plot_div = plot(fig, output_type='div', filename='Logarithm of residuals for 8 groups') return plot_div
def box_plot(data,Analysis_column): st.header('**Data Analysis**') box_train = data box_train['ds'] = pd.to_datetime(box_train['ds']) box_train['Hourly'] = box_train['ds'].dt.hour box_train['Daily'] = box_train['ds'].dt.day box_train['Monthly'] = box_train['ds'].dt.month box_train['Yearly'] = box_train['ds'].dt.year daily = box_train.groupby(['Daily'],as_index=False)['y'].mean() Monthly = box_train.groupby(['Monthly'],as_index=False)['y'].mean() Yearly = box_train.groupby(['Yearly'],as_index=False)['y'].mean() fig = make_subplots(rows=3, cols=2) fig.add_trace( go.Scatter(x=daily.index,y=daily['y'], name='Daily Trend'), row = 1, col=1 ) fig.add_trace( go.Box(x=box_train['Daily'],y=box_train['y'], name='Daily Trend BoxPlot'), row = 1, col=2 ) fig.add_trace( go.Scatter(x=Monthly.index,y=Monthly['y'], name='Monthly Trend'), row = 2, col=1 ) fig.add_trace( go.Box(x=box_train['Monthly'],y=box_train['y'], name='Monthly Trend BoxPlot'), row = 2, col=2 ) fig.add_trace( go.Scatter(x=Yearly['Yearly'],y=Yearly['y'], name='Yearly Trend'), row = 3, col=1 ) fig.add_trace( go.Box(x=box_train['Yearly'],y=box_train['y'], name='Yearly Trend BoxPlot'), row = 3, col=2 ) fig.update_xaxes(title_text = 'Daily Time Period', row=1, col =1) fig.update_xaxes(title_text = 'Monthly Time Period', row=2, col =1) fig.update_xaxes(title_text = 'Yearly Time Period', row=3, col =1) fig.update_yaxes(title_text = Analysis_column, row=1, col =1) fig.update_yaxes(title_text = Analysis_column, row=2, col =1) fig.update_yaxes(title_text = Analysis_column, row=3, col =1) fig.update_layout( plot_bgcolor = '#FFF', autosize=False, width=1100, height=1000, ) st.plotly_chart(fig)
def update_statistics_charts(project, subject, gender, race, age): if project == 'all': project = data.project.unique() else: project = [project] if not subject: return px.box(), px.box() elif 'all' in subject: subject = data.person.unique() else: subject = subject if gender == 'all': gender = data.gender.unique() else: gender = [gender] if not race: return px.box(), px.box() elif 'all' in race: race = data.race.unique() else: race = race mask = ((data.project.isin(project)) & (data.person.isin(subject)) & (data.gender.isin(gender)) & (data.race.isin(race)) & ((data.age <= age[1]) & (data.age >= age[0]))) filtered_data = data.loc[mask, :] mape_chart_figure = { "data": [ go.Box(x=filtered_data['mape'], y=filtered_data['activity'], orientation='h') ], "layout": go.Layout(title='MAPE vs Activity'), } da_chart_figure = { "data": [ go.Box(x=filtered_data['da'], y=filtered_data['activity'], orientation='h') ], "layout": go.Layout(title='Data Availability vs Activity'), } return mape_chart_figure, da_chart_figure
def plot_cps(): Y_entrees_cps = [] Y_breakfast_entrees_cps = [] Y_ventrees_cps = [] Y_desserts_cps = [] get_calories_per_serving(12, Y_entrees_cps) get_calories_per_serving(2, Y_breakfast_entrees_cps) get_calories_per_serving(13, Y_ventrees_cps) get_calories_per_serving(17, Y_desserts_cps) fig = go.Figure() fig.add_trace( go.Box(x=Y_entrees_cps, marker_color=primary_colors[0], name='Entrees', boxpoints='outliers')) fig.add_trace( go.Box(x=Y_breakfast_entrees_cps, marker_color=primary_colors[1], name='Breakfast Entrees', boxpoints='outliers')) fig.add_trace( go.Box(x=Y_ventrees_cps, marker_color=primary_colors[2], name='Vegetarian Entrees', boxpoints='outliers')) fig.add_trace( go.Box(x=Y_desserts_cps, marker_color=primary_colors[3], name='Desserts', boxpoints='outliers')) fig.update_layout( title='Calories per Serving of HUDS Entrees and Desserts', xaxis=dict(tickmode='linear', tick0=0, dtick=5, title={'text': 'Calories per Ounce or Fluid Ounce'}), xaxis_range=[0, 130], yaxis={'title': { 'text': 'Food Categories' }}, legend={'title': { 'text': 'Groups' }}, template=theme_hodp) fig.show()
def update_box(hoverData1,hoverData2, var1,var2, type): """Updates box plot in response to change in granularity, vars, or which precinct user is hovering over""" if type == 'Precincts': try: precinctkey1 = hoverData1['points'][0]['location'] precinctkey2 = hoverData2['points'][0]['location'] except TypeError: precinctkey1 = 270402 precinctkey2 = 270402 merged1 = aggregate('Precincts', var1,resultscatalog) merged2 = aggregate('Precincts',var2,resultscatalog) df1 = merged1[['PrecinctKey',var1]] df2 = merged2[['PrecinctKey',var2]] index1 = df1.index[df1['PrecinctKey'] == precinctkey1].tolist() index2 = df2.index[df2['PrecinctKey'] == precinctkey2].tolist() box =make_subplots(rows=1,cols=2) box.add_trace(go.Box(y=df1[var1], boxpoints='all', name=var1,text=df1['PrecinctKey'],hoverinfo='y+text',selectedpoints=index1, hovertemplate="PrecinctKey: %{text} | Value: %{y}<extra></extra>"), row=1,col=1) box.add_trace(go.Box(y=df2[var2], boxpoints='all', name=var2,text=df2['PrecinctKey'],hoverinfo='y+text',selectedpoints=index2, hovertemplate="PrecinctKey: %{text} | Value: %{y}<extra></extra>"), row=1,col=2) box.update_layout(showlegend=False) else: #for zipcode mappings try: zip1 = hoverData1['points'][0]['location'] zip2 = hoverData2['points'][0]['location'] except TypeError: zip1 = 76543 zip2 = 76543 merged1 = aggregate('Zipcodes',var1,resultscatalog) merged2 = aggregate('Zipcodes',var2,resultscatalog) df1 = merged1[['zipcode',var1]] df2 = merged2[['zipcode',var2]] index1 = df1.index[df1['zipcode'] == zip1].tolist() index2 = df2.index[df2['zipcode'] == zip2].tolist() box =make_subplots(rows=1,cols=2) box.add_trace(go.Box(y=df1[var1], boxpoints='all', name=var1,text=df1['PrecinctKey'],hoverinfo='y+text',selectedpoints=index1, hovertemplate="PrecinctKey: %{text} | Value: %{y}<extra></extra>"), row=1,col=1) box.add_trace(go.Box(y=df2[var2], boxpoints='all', name=var2,text=df2['PrecinctKey'],hoverinfo='y+text',selectedpoints=index2, hovertemplate="PrecinctKey: %{text} | Value: %{y}<extra></extra>"), row=1,col=2) box.update_layout(showlegend=False) return box
def box_plot(df, xaxis, yaxis, boxpt, boxaxis): fig = go.Figure() if boxpt=='False': boxpt=False if boxaxis == 'xaxis': fig.add_trace(go.Box(x=df[xaxis], boxpoints=boxpt, name=f'{xaxis}', marker_color='#636EFA')) elif boxaxis == 'yaxis': fig.add_trace(go.Box(x=df[yaxis], boxpoints=boxpt, name=f'{yaxis}', marker_color='#19D3F3')) else: fig.add_trace(go.Box(x=df[xaxis], boxpoints=boxpt, name=f'{xaxis}', marker_color='#636EFA')) fig.add_trace(go.Box(x=df[yaxis], boxpoints=boxpt, name=f'{yaxis}', marker_color='#19D3F3')) fig.update_xaxes(showgrid=False, zeroline=False) fig.update_yaxes(showgrid=False, zeroline=False) fig.update_layout(plot_bgcolor='rgb(255,255,255)', height=450, width=1200) return fig
def plot_boxplots(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list): tmp = filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list) # TODO CODE # Histogram with all outliers combined as e.g. >30 hours # return figure fig = make_subplots(rows=1,cols=4) fig.append_trace(go.Box(y=tmp.event_si, name="Severity",marker=dict(color=color_set[0])),row=1,col=1) fig.append_trace(go.Box(y=tmp.event_area, name="Area",marker=dict(color=color_set[1])),row=1,col=2) fig.append_trace(go.Box(y=tmp.event_pre, name="Precipitation",marker=dict(color=color_set[2])),row=1,col=3) fig.append_trace(go.Box(y=tmp.event_length, name="Duration",marker=dict(color=color_set[3])),row=1,col=4) fig.update_layout(title="Dispertion of Attributes",legend=dict(orientation="h")) return fig
def boxplot(df, title='Box-Plot', out_path=None, layout_width=None, layout_height=None, numeric_only=True): data = [] columns = [ k for k, v in df.dtypes.items() if 'float' in str(v) or 'int' in str(v) ] if numeric_only else df.columns for column in columns: data.append( go.Box( y=df[column], boxpoints='outliers', # all, outliers, suspectedoutliers boxmean=True)) max_col = 2 subplot_titles = [f'{x.lower()}' for x in columns] plot_subplots(data, max_col, title, subplot_titles=subplot_titles, out_path=out_path, layout_width=layout_width, layout_height=layout_height)
def plot_corr_box_plot(self, x_axis_column_name, y_axis_column_name, scale): fig = make_subplots(rows=1, cols=1) shared_bins_cond = None for plot_df, method_name, j in zip(self.plot_dfs, self.method_names, range(len(self.plot_dfs))): plot_df = filter_by_scale(scale, plot_df) # plot_df = plot_df[(np.log2(plot_df[x_axis_column_name]+1) >=1) & (np.log2(plot_df[y_axis_column_name]+1) >= 1)] df, shared_bins_cond = prepare_corr_box_plot_data( np.log2(plot_df[y_axis_column_name] + 1), np.log2(plot_df[x_axis_column_name] + 1), shared_bins_cond) fig.add_trace(go.Box(x=df['true_abund'], y=df['estimated_abund'], name=method_name), col=1, row=1) fig.update_xaxes(title_text='Log2(True TPM+1)') fig.update_yaxes(title_text='Log2(Estimated TPM+1)') fig.update_layout(boxmode="group", autosize=False, showlegend=True, width=fig_size['square']['width'], height=fig_size['square']['height'], template=themes['large_single']) return fig
def plot_normalized_demand(data): """ Plot Tempearture Normalized Demand based on Heating and Cooling degree days Input: Data from 2010 - 2020 Returns: Figure """ temp_df = data[["AIL_DEMAND", "Degree_days"]].copy() temp_df = temp_df.groupby(by=temp_df.index.date).sum() temp_df.index = pd.to_datetime(temp_df.index) temp_df['Normalized_AIL_Demand'] = temp_df.AIL_DEMAND / temp_df.Degree_days fig = go.Figure() for year in range(2010, 2021): fig.add_trace( go.Box( x=temp_df[temp_df.index.year == year].index.year, y=temp_df['Normalized_AIL_Demand'][temp_df.index.year == year], name=str(year))) fig.update_layout( title= "Distribition of Daily Demand per Heating/Cooling Degree Days (Base = 18 Celsius) " ) return fig
def box(df, title='Box', color=None, out_path=None, max_col=2, layout_kwargs={}, to_image=False, box_kwargs={}): columns = df.select_dtypes(include='number') columns = [x for x in columns if x != color] data_groups = [] groups = [1] if color is None else df[color].unique() for column in columns: data = [] colors = DEFAULT_PLOTLY_COLORS for index, group in enumerate(groups): data.append(go.Box( y=df[column] if color is None else df[df[color] == group][column], name=column if color is None else group, marker={'color': colors[index % len(colors)]}, **box_kwargs )) data_groups.append(data) if color is None: layout_kwargs['showlegend'] = False datagroups_subplots(data_groups, max_col=max_col, title=title, out_path=out_path, yaxis_titles=[] if color is None else columns, layout_kwargs=layout_kwargs, to_image=to_image)