def render_content(tab): if tab == "tab-1-example": return html.Div( [ html.H3("Tab content 1"), dcc.Graph( id="graph-1-tabs", figure={ "data": [{"x": [1, 2, 3], "y": [3, 1, 2], "type": "bar"}] }, ), ] ) elif tab == "tab-2-example": return html.Div( [ html.H3("Tab content 2"), dcc.Graph( id="graph-2-tabs", figure={ "data": [{"x": [1, 2, 3], "y": [5, 10, 6], "type": "bar"}] }, ), ] )
def get_polar_html(old_code="02150", new_code="00100"): # H1 location_string = f"Hey, how about this one? {zip_name_dict[new_code]}, {new_code}" # H2 sell_price_string = get_attribute(postalcode=new_code, column="Sell price") sell_price_string = f"{float(sell_price_string):.2f}" if sell_price_string != "0.0" else "--" rent_ara_price_string = get_attribute(postalcode=new_code, column="Rent price with ARA") rent_ara_price_string = f"{float(rent_ara_price_string):.2f}" if rent_ara_price_string != "0.0" else "--" rent_noara_price_string = get_attribute(postalcode=new_code, column="Rent price without ARA") rent_noara_price_string = f"{float(rent_noara_price_string):.2f}" if rent_noara_price_string != "0.0" else "--" trend_near_future_string = f"{float(get_attribute(new_code, column='Trend near future')):+.2%}" # H3 average_age_string = get_attribute(postalcode=new_code, column="Average age of inhabitants") categories = [ 'Education', 'Services', 'Public Transportation', 'Average Income', 'Population Density' ] fig = go.Figure() fig.add_trace( go.Scatterpolar(r=radar_value(old_code), theta=categories, fill='toself', name='Current location')) fig.add_trace( go.Scatterpolar(r=radar_value(new_code), theta=categories, fill='toself', name='New location')) fig.update_layout(polar=dict(radialaxis=dict(range=[0, 1])), margin={ "r": 20, "t": 50, "l": 20, "b": 20 }) return html.Div( children=[ html.H1(location_string), html.H2(f"🛈 Last 12 months sell price: {sell_price_string} €/m²", id="sell_12"), html. H2(f"🛈 Last 12 months rent price: {rent_ara_price_string} €/m² (including ARA), {rent_noara_price_string} €/m² (private only)", id="rent_12"), html.H3(f"Trend of price: {trend_near_future_string}"), html.H3(f"Average age: {average_age_string} years"), # html.H3(percentage_degree + "% of the people has a higher university degree"), make_dash_table(old_code, new_code), dcc.Graph(figure=fig, id="polar_graph", config={'displayModeBar': False}) ], id="analysis_info")
def update_reports_list(iso_code): reports = reliefweb_api.get_reports_for_country(iso_code) if not reports: return '' images = [ html.A(children=[ html.Img(src=report['thumbnail'], style={ 'height': '180px', 'padding': '3', 'marginRight': 40, 'marginLeft': 40, 'boxShadow': '10px 10px 5px 0px #656565', 'background': '#FFF' }), html.P(report['title'][0:50], style={ 'font-size': 'small', 'text-align': 'center' }) ], href=report['file'], target='_blank') for report in reports ] return html.Div([ html.H3('Humanitarian Reports'), html.Div(children=images, style={ 'display': 'flex', 'align': 'middle', 'flexDirection': 'row', 'justifyContent': 'center' }) ])
def get_country_table(df, year): return html.Div([ html.H3('Needs - Data from {0}'.format(year)), html.Table([ html.Tr([ html.Th([col], style={'text-align': 'center'}) for col in [ '', html.I(className="fas fa-percent fa-lg"), html.I(className="fas fa-child fa-lg"), html.I(className="fas fa-box fa-lg") ] ]) ] + [ html.Tr([ html.Th(col['title']), html.Td(df[col['type']]), html. Td(functions.format_number_col(df[col['type'] + '_children'])), html.Td(get_needs_kg(df, col['type'])) ], style={'color': col['color']}) for col in [ { 'title': 'Severe Wasting', 'type': 'severe_wasting', 'color': SEVERE_WASTING_COLOR }, { 'title': 'Moderate Wasting', 'type': 'moderate_wasting', 'color': MODERATE_WASTING_COLOR }, { 'title': 'Overall Wasting', 'type': 'wasting', 'color': WASTING_COLOR }, { 'title': 'Stunting', 'type': 'stunting', 'color': STUNTING_COLOR }, { 'title': 'Overweight', 'type': 'overweight', 'color': OVERWEIGHT_COLOR }, { 'title': 'Underweight', 'type': 'underweight', 'color': UNDERWEIGHT_COLOR }, ] ]), html.Div(children=[ html.P('Source : ' + df['source'].astype(str)), html.P('By : ' + df['report_author'].astype(str)) ], style={'font-size': 'x-small'}) ], style={'font-size': 'small'})
def cell_clicked_processed(cell, data): if cell is None: return dash.no_update row, col = cell["row"], cell["column_id"] selected = data[row][col] if selected is not None: dataset_id = data[row]['Dataset ID'] processed_datasets_df = config.processed_datasets_df.set_index( 'Dataset ID') datasets_df = config.datasets_df.set_index('Dataset ID') link = processed_datasets_df.loc[dataset_id, "Link"] options = processed_datasets_df.loc[dataset_id, "Options"] if type(options) == str: options = json.loads(options) options_str = json.dumps(options, indent=2) else: options_str = "None" short_type = data[row]['Short Type'] if short_type == "D": obj = pyrplib.dataset.ProcessedD.from_json(link).load() description = datasets_df.loc[obj.source_dataset_id, "Description"] dataset_name = datasets_df.loc[obj.source_dataset_id, "Dataset Name"] command = obj.command unprocessed_source_id = obj.source_dataset_id unprocessed = pyrplib.dataset.load_unprocessed( unprocessed_source_id, datasets_df) index = processed_datasets_df.loc[dataset_id, "Index"] description = description.replace("\\n", "\n") contents = [ html.Br(), html.H2(dataset_name), html.H3("Description"), html.Pre(description), html.H3("Command"), html.Pre(command), html.H3("Options"), html.Pre(options_str) ] + [ html.H3("Source Item data") ] + unprocessed.view_item(index) + [html.H3("Data")] + obj.view() return html.Div(contents) else: return dash.no_update
def create_and_plot_sample(distribution: str, size: int, *parameters) -> tuple: """Create a sample of the specified distribution using the provided parameters, then plot a histogram & violin-plot, and compute descriptive statistics. Parameters ---------- distribution : str The name of the currently selected distribution size : int The set sample size *parameters : int, float 1 or 2 parameter values, depending on the distribution Returns ------- tuple A histogram, a violin_plot, an ecdf-plot, a table of summary statistics, the currently specified parameters and a csv file with the sample data for download. """ sample = process_random_sample(distribution, size, parameters) histogram = plotting.plot_histogram(sample["data"], distribution) violin_plot = plotting.plot_violin(sample["data"], distribution) ecdf_plot = plotting.plot_ecdf(sample["data"], distribution) summary_statistics = sample["summary_statistics"] summary_statistics_table = [html.Th("Summary Statistics")] + [ html.Tr([html.Td(f"{name}:"), html.Td(value)]) for name, value in summary_statistics.items() ] parameters = sample["parameters"] param_dict = { distribution_data[distribution].get(f"param{idx}"): value for idx, value in enumerate(parameters, start=1) } param_dict["Sample Size"] = size parameter_info = [ html.H3("Parameters: "), html.P([ ", ".join([f"{key}: {value}" for key, value in param_dict.items()]) ]), ] sample_csv_download = { "content": sample["data"].to_csv(index=False), "filename": f"{distribution}-sample.csv", "type": "text/csv", } return ( histogram, violin_plot, ecdf_plot, summary_statistics_table, parameter_info, sample_csv_download, )
def code_breakdown(): """Show the code break down.""" report_directory = "D:\\\\Projects\\github\\sqatt\\reports" container = html.Div([ html.H3("Code type breakdown"), dbc.Row( dbc.Col( dcc.Graph(id="code_type", figure=code_type_breakdown(report_directory)))), html.H3("Code volume breakdown"), dbc.Row( dbc.Col( dcc.Graph(id="code_volume", figure=code_volume_breakdown(report_directory)))), ]) return container
def test_rdls001_multi_loading_components(dash_duo): lock = Lock() app = Dash(__name__) app.layout = html.Div(children=[ html.H3("Edit text input to see loading state"), dcc.Input(id="input-3", value="Input triggers the loading states"), dcc.Loading( className="loading-1", children=[html.Div(id="loading-output-1")], type="default", ), html.Div([ dcc.Loading( className="loading-2", children=[html.Div([html.Div(id="loading-output-2")])], type="circle", ), dcc.Loading( className="loading-3", children=dcc.Graph(id="graph"), type="cube", ), ]), ], ) @app.callback( [ Output("graph", "figure"), Output("loading-output-1", "children"), Output("loading-output-2", "children"), ], [Input("input-3", "value")], ) def input_triggers_nested(value): with lock: return dict(data=[dict(y=[1, 4, 2, 3])]), value, value def wait_for_all_spinners(): dash_duo.find_element(".loading-1 .dash-spinner.dash-default-spinner") dash_duo.find_element(".loading-2 .dash-spinner.dash-sk-circle") dash_duo.find_element(".loading-3 .dash-spinner.dash-cube-container") def wait_for_no_spinners(): dash_duo.wait_for_no_elements(".dash-spinner") with lock: dash_duo.start_server(app) wait_for_all_spinners() wait_for_no_spinners() with lock: dash_duo.find_element("#input-3").send_keys("X") wait_for_all_spinners() wait_for_no_spinners()
def render(self, dashboard): return html.Div(children=[ html.H2(self.title), html.H3(self.meta["timestamp"]), dcc.Markdown(self.description), html.Pre(self.meta["env"]["uname"]), self._render(dashboard) ], className="dashboard-object")
def format_additional_content(self): container = html.Div(children=[]) for content in self._record["additional_content"]: div = html.Div(children=[html.H3(content["title"]), html.Br()]) for image in content["images"]: div.children.append(self.format_image(image)) div.children.append(html.P(content["body"])) div.children.append(html.Br()) container.children.append(div) return container
def file_size_metrics(): """Determine the function metrics.""" container = html.Div([ html.H3("File size"), dcc.Graph(id="File size", figure=make_my_profile(get_file_size_metrics(), "File size")), ]) return container
def generate_funding_info(funding_data): data = json.loads(funding_data)['country_funding'] if data['total_funded'] == 0: return '' return html.Div([ html.H3('Nutrition funding details in the country'), html.P('Total funded for nutrition: {0}$'.format( format(data['total_funded'], ','))) ])
def get_about_html(): text = """ This is the implementation of our Data Science Project. The aim of this project is to provide suggestions on suitable relocation areas in Finland, based on housing prices and demographics. """ return html.Div([ html.H1("About"), html.H3(text, id="about_text"), html.H1("Team"), html.Table([ html.Thead( html.Tr([ html.Th("Letizia"), html.Th("Taige"), html.Th("Roope"), html.Th("Trang"), html.Th("Thong") ])), html.Tbody( html.Tr([ html.Td( html.A(html.Img( src= "https://avatars1.githubusercontent.com/u/45148109?s=200&v=4", alt="Letizia"), href="https://github.com/letiziaia")), html.Td( html.A(html.Img( src= "https://avatars2.githubusercontent.com/u/16875716?s=200&v=4", alt="Taige"), href="https://github.com/xiaoxiaobt")), html.Td( html.A(html.Img( src= "https://avatars2.githubusercontent.com/u/43811718?s=200&v=4", alt="Roope"), href="https://github.com/rooperuu")), html.Td( html.A(html.Img( src= "https://avatars3.githubusercontent.com/u/55182434?s=200&v=4", alt="Trang"), href="https://github.com/trangmng")), html.Td( html.A(html.Img( src= "https://avatars0.githubusercontent.com/u/32213097?s=200&v=4", alt="Thong"), href="https://github.com/trananhthong")) ])) ], id="team_table") ], id="about_info")
def code_duplication(): """Determine the code duplication.""" report_file = "D:\\\\Projects\\github\\sqatt\\reports\\code_duplication.csv" metrics = get_duplication_metrics(report_file) content = html.Div( [html.H3("Code duplication"), dcc.Graph(id="code_duplication", figure=code_duplication_figure(metrics))], ) return content
def function_metrics(): """Determine the function metrics.""" container = html.Div([ html.H3("Complexity"), dcc.Graph(id="complexity", figure=make_my_profile(get_metrics("Complexity"), "Complexity")), html.H3("Function size"), dcc.Graph(id="function_size", figure=make_my_profile(get_metrics("Function size"), "Function size")), html.H3("Function parameters"), dcc.Graph( id="function_parameters", figure=make_my_profile(get_metrics("Function parameters"), "Function parameters"), ), ]) return container
def format_associations(self): assocs = self._record["associations"] div = html.Div(children=[]) if len(self._record["associations"]) > 0: div.children.append(html.H3("Associations")) div.children.append(html.Br()) for assoc in self._record["associations"]: div.children.append( html.P("{}, {}".format(assoc["name"], assoc["type"]))) div.children.append(html.Br()) return div
def show_document(match: dict): url = f"/pdf/{match['pdf']}" iframe = dbc.Row( dbc.Col(html.Iframe(src=url, style={ "width": "100%", "height": "100%" })), style={ "resize": "vertical", "overflow-y": "hidden", "height": "1000px", "min-height": "100px", }, ) title = match["title"].replace("_", " ") title = " ".join([w.capitalize() for w in title.split()]) title = dbc.Row(dbc.Col(html.H3(title))) date = html.A( match["date"], id={ "type": "link_date", "date": match["date"] }, href="#", n_clicks=0, style={ "text-decoration": "none", "color": "inherit" }, ) tags = html.P([ dbc.Badge( tag, id={ "type": "link_tag", "tag": tag }, href="#", n_clicks=0, color="primary", className="mr-1", ) for tag in match["tags"] ]) data = dbc.Table( [ html.Tbody([ html.Tr([html.Td("Date"), html.Td(date)]), html.Tr([html.Td("Tags"), html.Td(tags)]), ]) ], striped=True, ) return dbc.Row([dbc.Col([title, data], width=4), dbc.Col(iframe)])
def language_breakdown(): """Create the language break down.""" report_file = "D:\\\\Projects\\github\\sqatt\\reports\\language_profile.csv" metrics = get_language_metrics(report_file) content = html.Div([ html.H3("Language breakdown"), dcc.Graph(id="language_breakdown", figure=language_breakdown_figure(metrics)) ], ) return content
def cell_clicked_dataset(cell, data): if cell is None: return dash.no_update row, col = cell["row"], cell["column_id"] selected = data[row][col] dataset_id = data[row]['Dataset ID'] dataset_name = data[row]['Dataset Name'] datasets_df = config.datasets_df.set_index('Dataset ID') links = datasets_df.loc[dataset_id, 'Download links'] loader = datasets_df.loc[dataset_id, 'Loader'] description = str(datasets_df.loc[dataset_id, 'Description']) if selected is not None: unprocessed = pyrplib.dataset.load_unprocessed( dataset_id, datasets_df) description = description.replace("\\n", "\n") description_html = [html.H3("Description"), html.Pre(description)] contents = [ html.Br(), html.H2(dataset_name) ] + description_html + [html.H3("Data")] + unprocessed.view() return html.Div(contents) else: return dash.no_update
def format_pulsar_paramters(self): pp = self._record["pulsar_parameters"] return html.Div(children=[ html.H3("Pulsar Parameters"), html.Br(), html.P(["Period: {} ms".format(pp["period"])]), html.P( dcc.Markdown("Dispersion measure: {} pc cm<sup>-3</sup>". format(pp["dm"]), dangerously_allow_html=True)), html.P("Binary: {}".format(pp["binary"])), html.Br() ])
def format_discovery_parameters(self): dp = self._record["discovery_parameters"] return html.Div(children=[ html.H3("Discovery details"), html.Br(), html.P("Discovery date: {}".format(dp["discovery_date"])), html.P("Observation date: {}".format(dp["observation_date"])), html.P("Observation band: {}".format(dp["discovery_band"])), html.P("Discovery S/N: {}".format(dp["discovery_snr"])), html.P("Pipeline: {}".format(dp["pipeline"])), html.P("Project: {}".format(dp["project"])), html.Br() ])
def cards_view(): """ card layout """ cards = [ dbc.Row([ dbc.Col(dbc.Card([ html.P("Resting Heart Rate Average", className="card-text"), html.H3(id='RestingHeartRate', className="card-title"), ], body=True, color="light", style={'height': '100%'}), sm=4), dbc.Col(dbc.Card([ html.P("Walking Heart Rate Average", className="card-text"), html.H3(id='WalkingHeartRate', className="card-title"), ], body=True, color="light", style={'height': '100%'}), sm=4), dbc.Col(dbc.Card([ html.P("Average Heart Rate", className="card-text"), html.H3(id='HeartRate_mean', className="card-title"), ], body=True, color="light", style={'height': '100%'}), sm=4) ]), html.Br(), dbc.Row([ dbc.Col(dbc.Card([ html.P("Steps", className="card-text"), html.H3(id='step', className="card-title"), ], body=True, color="light", style={'height': '100%'}), sm=4), dbc.Col(dbc.Card([ html.P("Active Calories", className="card-text"), html.H3(id='ActivitySummary', className="card-title"), ], body=True, color="light", style={'height': '100%'}), sm=4), dbc.Col(dbc.Card([ html.P("Exercise minutes ", className="card-text"), html.H3(id='Exercise_minute', className="card-title"), ], body=True, color="light", style={'height': '100%'}), sm=4) ]) ] return cards
def get_project_dropdown(df: pd.DataFrame): projects = sorted(list(df["project_name"].unique())) return html.Div( dbc.Col( [ html.Br(), html.H3("Select a Project", style={"textAlign": "left"}), dcc.Dropdown( id="project_name", options=[{ "label": i, "value": i } for i in projects], value=projects[0], ), ], style={"display": "inline-block"}, ))
def log_layout(): with open(LOG_FILE, "r", encoding="utf-8") as f: log_text = f.read() return html.H3(className="m-2", children=[ "Log:", dbc.Container(fluid=True, style={ "height": "80vh", "overflow": "auto", "display": "flex", "flex-direction": "column-reverse", "white-space": "pre-line" }, children=log_text, className="m-3 bg-light h5"), html.Div(id="empty-div") ])
def view(self): """ Standard view function for a dataset """ data = self.dash_ready_data() if len(data) == 1: html_comps = [] for j in range(len(data.columns)): d = data.iloc[0,j] html_comps.append(html.H3(data.columns[j])) if type(d) == pd.DataFrame: html_comps.append(style.get_standard_data_table(d,f"data_view_{j}")) elif type(d) == list: html_comps.append(html.Pre("\n".join(d))) else: html_comps.append(html.Pre(d)) return html_comps else: return [style.get_standard_data_table(data.reset_index(),"data_view")]
def get_relief_web_data(selected_iso_code): country_data = relief_web_data[relief_web_data['crisis_iso3'] == selected_iso_code].sort_values( 'figure_name') if len(country_data) == 0: return '' return html.Div([ html.H3('Relief Web Crisis App Data'), dash_table.DataTable( data=country_data.to_dict('records'), columns=[{ "name": i, "id": i } for i in [ 'figure_name', 'figure_value', 'figure_date', 'figure_source' ]], row_selectable=False, editable=False, id='reliefweb-datatable') ])
def test_mdcap001_dcc_components_as_props(dash_dcc): app = Dash(__name__) app.layout = html.Div( [ dcc.Checklist( [ {"label": html.H2("H2 label"), "value": "h2"}, {"label": html.A("Link in checklist", href="#"), "value": "a"}, ], id="checklist", ), dcc.RadioItems( [ {"label": html.H3("on"), "value": "on"}, {"label": html.P("off"), "value": "off"}, ], id="radio-items", ), dcc.Dropdown( [ {"label": html.H4("h4"), "value": "h4"}, {"label": html.H6("h6"), "value": "h6"}, ], id="dropdown", ), ] ) dash_dcc.start_server(app) dash_dcc.wait_for_text_to_equal("#checklist h2", "H2 label") dash_dcc.wait_for_text_to_equal("#checklist a", "Link in checklist") dash_dcc.wait_for_text_to_equal("#radio-items h3", "on") dash_dcc.wait_for_text_to_equal("#radio-items p", "off") dash_dcc.find_element("#dropdown").click() dash_dcc.wait_for_text_to_equal("#dropdown h4", "h4") dash_dcc.wait_for_text_to_equal("#dropdown h6", "h6")
def dashSubplot(plots, min_width=18, # min width of column (in %). If more columns, scrolling is enabled max_width=50, # max width of column (in %). indiv_widths=None, # can specify list of individual column widths title='' # str or list of strs ): if isinstance(title, str): title = [title] # remove empty elements of list plots = [[plt for plt in col if plt != []] for col in plots] # remove empty plots from each column for i in range(len(plots)-1, -1, -1): # remove empty columns if plots[i] == []: plots.pop(i) if indiv_widths is not None: indiv_widths.pop(i) Ncol = len(plots) # number of columns if indiv_widths is None: col_width = [min(max_width, max(int(100/Ncol-2), min_width) )] * Ncol else: col_width = indiv_widths title = sum([[i, html.Br()] for i in title], [])[:-1] col_style = [{'width': str(col_width[i]) + '%', 'display': 'inline-block', 'vertical-align': 'top', 'margin-right': '25px'} for i in range(Ncol)] plot_divs = html.Div([html.Div(plots[i], style=col_style[i]) for i in range(Ncol)]) title_div = html.H3(title) layout = html.Div(html.Div([title_div, plot_divs]), style={'margin-right': '0px', 'position': 'absolute', 'width': '100%'}) return layout
children=[ dash_table.DataTable(id='ws-table', columns=[{ "name": i, "id": i, "selectable": True } for i in ['Workspace']], data=[], row_selectable='single', row_deletable=False, style_cell={'textAlign': 'left'}, sort_action='native') ]) _layout = html.Div([ html.H3('Workspaces'), html.Button('Create Workspace', id='ws-create'), html.Button('Delete Workspace', id='ws-delete', style={'float': 'right'}), ws_table, dbc.Modal([ dbc.ModalHeader("Create Workspace"), dbc.ModalBody([ dcc.Input(id='ws-create-input', placeholder='New workspace name'), html.P(id='ws-create-output') ]), dbc.ModalFooter( html.Div([ dbc.Button("Create", id="ws-create-confirm", style={'marginRight': '10px'}), dbc.Button("Cancel", id="ws-create-cancel")
def update_graph(tickers): graphs = [] if not tickers: graphs.append( html.H3("Select a stock ticker.", style={ 'marginTop': 20, 'marginBottom': 20 })) else: for i, ticker in enumerate(tickers): dff = df[df['Stock'] == ticker] candlestick = { 'x': dff['Date'], 'open': dff['Open'], 'high': dff['High'], 'low': dff['Low'], 'close': dff['Close'], 'type': 'candlestick', 'name': ticker, 'legendgroup': ticker, 'increasing': { 'line': { 'color': colorscale[0] } }, 'decreasing': { 'line': { 'color': colorscale[1] } } } bb_bands = bbands(dff.Close) bollinger_traces = [{ 'x': dff['Date'], 'y': y, 'type': 'scatter', 'mode': 'lines', 'line': { 'width': 1, 'color': colorscale[(i * 2) % len(colorscale)] }, 'hoverinfo': 'none', 'legendgroup': ticker, 'showlegend': True if i == 0 else False, 'name': '{} - bollinger bands'.format(ticker) } for i, y in enumerate(bb_bands)] graphs.append( dcc.Graph(id=ticker, figure={ 'data': [candlestick] + bollinger_traces, 'layout': { 'margin': { 'b': 0, 'r': 10, 'l': 60, 't': 0 }, 'legend': { 'x': 0 } } })) return graphs