### Aptfile Example for Package Installation Source: https://dash.plotly.com/workspaces/apt-package-management.md Declare APT packages to be installed in your workspace by adding them to the Aptfile. This method is crucial for internet-restricted Dash Enterprise environments and ensures consistency between development and deployment. ```text Add the package to Aptfile in your workspace and rebuild. ``` -------------------------------- ### Install Required Packages Source: https://dash.plotly.com/all-in-one-components.md Install the necessary packages for the DataTableAIO example, including redis, fakeredis, and pyarrow. ```bash pip install pyarrow fakeredis redis ``` -------------------------------- ### Quickstart: Basic DataTable with Pandas Source: https://dash.plotly.com/datatable.md Create a basic Dash DataTable from a Pandas DataFrame. Ensure the 'pandas' library is installed. ```python from dash import Dash, dash_table import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv') app = Dash() app.layout = dash_table.DataTable(df.to_dict('records'), [{"name": i, "id": i} for i in df.columns]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Basic End-to-End Test Setup Source: https://dash.plotly.com/testing.md This snippet shows the initial imports required for a Dash application and the setup for a test case using a test ID. It's the starting point for writing end-to-end tests. ```python # 1. imports of your dash app import dash from dash import html # 2. give each testcase a test id, and pass the fixture ``` -------------------------------- ### Import Dash DAQ and Print Version Source: https://dash.plotly.com/dash-daq.md Demonstrates how to import the dash_daq library and print its installed version. This is a common first step when starting with the library. ```python import dash_daq as daq print(daq.__version__) ``` -------------------------------- ### Quickstart: DataTable with Dash Enterprise Design Kit Source: https://dash.plotly.com/datatable.md Create a DataTable using the Dash Enterprise Design Kit, which allows for editable cells and theme customization. Ensure 'dash-design-kit' is installed. ```python from dash import Dash, dash_table import pandas as pd import dash_design_kit as ddk df = pd.read_csv('https://git.io/Juf1t') app = Dash() app.layout = ddk.App(show_editor=True, children=[ ddk.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), editable=True ) ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Install Dash Enterprise Libraries Source: https://dash.plotly.com/dash-enterprise/deployment.md Install the Dash Enterprise CLI and its associated libraries. Ensure you have Python 3.8-3.11 and Git installed. Replace the example URL with your Dash Enterprise package URL. ```bash pip install dash-enterprise-libraries --extra-index-url https:///packages ``` -------------------------------- ### Install Dash Player Source: https://dash.plotly.com/dash-player.md Install the dash-player package using pip. ```bash pip install dash-player ``` -------------------------------- ### Install Build Tool Source: https://dash.plotly.com/dash-plugins-using-hooks.md Install the 'build' package for creating installable Python packages. ```bash pip install build ``` -------------------------------- ### app.setup_startup_routes Source: https://dash.plotly.com/reference.md Initializes the startup routes stored in `STARTUP_ROUTES`. ```APIDOC ## `app.setup_startup_routes` ### Description Initialize the startup routes stored in STARTUP_ROUTES. ``` -------------------------------- ### Circos Backgrounds Configuration Example Source: https://dash.plotly.com/dash-bio/circos.md Example of how to configure backgrounds for a Circos plot track, including start, end, color, and opacity. ```json { backgrounds: [ { start: 0.006, color: '#4caf50', opacity: 0.1 }, { start: 0.002, end: 0.006, color: '#d3d3d3', opacity: 0.1 }, { end: 0.002, color: '#f44336', opacity: 0.1 } ] } ``` -------------------------------- ### Initialize Startup Routes Source: https://dash.plotly.com/reference.md Use app.setup_startup_routes() to initialize the startup routes stored in STARTUP_ROUTES. This method returns None. ```python app.setup_startup_routes( ) -> None ``` -------------------------------- ### Basic DashCanvas Setup Source: https://dash.plotly.com/canvas.md Demonstrates the basic initialization of a DashCanvas component in a Dash application layout. ```python from dash import Dash, html from dash_canvas import DashCanvas app = Dash() app.config.suppress_callback_exceptions = True app.layout = html.Div([ html.H5('Press down the left mouse button and draw inside the canvas'), DashCanvas(id='canvas_101') ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Install Pandas with Conda and Django with Pip Source: https://dash.plotly.com/dash-enterprise/application-structure/django-app.md Example environment.yml file demonstrating how to install pandas using Conda and Django using pip. This specifies package versions and Conda channels. ```yaml name: django-app channels: - conda-forge dependencies: - pip==21.2.4 - pip: - Django==4.2.5 - gunicorn==20.0.4 ``` -------------------------------- ### Default Power Button Example Source: https://dash.plotly.com/dash-daq/powerbutton.md A basic example demonstrating the default Power Button with its state managed by a callback. ```Python from dash import Dash, html, Input, Output, callback import dash_daq as daq app = Dash() app.layout = html.Div([ daq.PowerButton( id='our-power-button-1', on=False ), html.Div(id='power-button-result-1') ]) @callback( Output('power-button-result-1', 'children'), Input('our-power-button-1', 'on') ) def update_output(on): return f'The button is {on}.' if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Example Build Log Output Source: https://dash.plotly.com/plotly-cloud/logs.md This snippet shows typical output from build logs when Plotly Cloud automatically identifies and installs application dependencies. It indicates the dependencies found and the installation process. ```text Dependencies identified: dash numpy plotly pandas ... were found and will be installed. To provide your own dependencies, specify a requirements.txt or pyproject.toml. ... ``` -------------------------------- ### Date Range Picker Example Source: https://dash.plotly.com/dash-core-components.md Shows how to implement the dcc.DatePickerRange component for selecting a start and end date. ```python from dash import Dash, dcc, html from datetime import date app = Dash() app.layout = html.Div([ dcc.DatePickerRange( id='date-picker-range', start_date=date(1997, 5, 3), end_date_placeholder_text='Select a date!' ) ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Check Dash Bio Version Source: https://dash.plotly.com/dash-bio.md Verify the installed version of Dash Bio. This is useful for ensuring compatibility with documentation examples. ```python import dash_bio print(dash_bio.__version__) ``` -------------------------------- ### Basic Checklist Example Source: https://dash.plotly.com/dash-core-components/checklist.md Creates a basic checklist with options and pre-selected values. Options are provided as a list of strings. ```python from dash import dcc dcc.Checklist( ['New York City', 'Montréal', 'San Francisco'], ['New York City', 'Montréal'] ) ``` -------------------------------- ### Simple Clipboard Example Source: https://dash.plotly.com/dash-core-components/clipboard.md Use the `target_id` property to specify which component's value should be copied. No callback is required for this basic setup. ```python from dash import Dash, dcc, html app = Dash() app.layout = html.Div([ dcc.Textarea( id="textarea_id", value="Copy and paste here", style={"height": 100}, ), dcc.Clipboard( target_id="textarea_id", title="copy", style={ "display": "inline-block", "fontSize": 20, "verticalAlign": "top", }, ), ]) if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Editable Example Setup Source: https://dash.plotly.com/dash-ag-grid/d3-value-formatters.md Sets up a simple rowData for an editable Ag-Grid table, intended for experimenting with different format specifiers and values. ```python import dash_ag_grid as dag from dash import Dash, html, dcc app = Dash() rowData = [ {"specifier": "$,.2f", "Default": 1000, "France": 1000, "Japan": 1000, "UK": 1000}, ] ``` -------------------------------- ### Use a Basic All-in-One Component in an App Source: https://dash.plotly.com/all-in-one-components.md Demonstrates how to integrate the custom `MarkdownWithColorAIO` component into a Dash application's layout. This example shows the simplest way to instantiate the component with just the required text. ```python from aio_components import MarkdownWithColorAIO from dash import Dash, html app = Dash() app.layout = MarkdownWithColorAIO('## Hello World') if __name__ == "__main__": app.run(debug=False) ``` -------------------------------- ### Install Package and Freeze Requirements Source: https://dash.plotly.com/workspaces/python-package-management.md Recommended method to install a package and automatically generate a `requirements.txt` file with version locking. This ensures dependencies are captured accurately. ```shell shell $ pip install $ pip freeze > requirements.txt ``` -------------------------------- ### Basic environment.yml with Pip Dependencies Source: https://dash.plotly.com/dash-enterprise/application-structure/dash-app.md Example environment.yml file specifying Conda channels and dependencies, including packages to be installed via pip. ```yaml name: my-conda-env channels: - conda-forge dependencies: - dash==2.4.1 - gunicorn==20.0.4 - pandas>=1.1.5 - pip: - dash-design-kit==1.6.7 ``` -------------------------------- ### Basic environment.yml for Streamlit App Source: https://dash.plotly.com/dash-enterprise/application-structure/streamlit-app.md This example shows a basic `environment.yml` file for a Streamlit app, installing pandas with Conda and Streamlit with pip. ```yaml name: streamlit-app channels: - conda-forge dependencies: - pip==21.2.4 - pandas==2.0.3 - pip: - streamlit==1.26.0 ``` -------------------------------- ### Print Report Setup and Callback Source: https://dash.plotly.com/dash-ag-grid/printing.md Sets up the Dash application, defines the grid configurations, and implements callbacks to open a print modal. The modal maintains the grid's current sort and filter states. The `domLayout: 'print'` option is used for the grid within the modal. ```Python import dash_ag_grid as dag from dash import Dash, html, dcc, Input, Output, State, callback import pandas as pd import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB]) df = pd.read_csv( "https://raw.githubusercontent.com/plotly/datasets/master/ag-grid/olympic-winners.csv" ) df = df.head(75) columnDefs = [ {"headerName": "ID", "valueGetter": {"function": "params.node.rowIndex + 1"}, "width": 70}, {"field": "country"}, {"field": "year"}, {"field": "athlete"}, {"field": "date"}, {"field": "sport"}, {"field": "total"}, ] defaultColDef = {"filter": True, "maxWidth": 150} grid = dag.AgGrid( id="grid-regular-layout", columnDefs=columnDefs, rowData=df.to_dict("records"), defaultColDef=defaultColDef, dashGridOptions={"animateRows": False} ) print_grid = dag.AgGrid( id="grid-modal-print", columnDefs=columnDefs, rowData=df.to_dict("records"), defaultColDef=defaultColDef, style={"height": "", "width": ""}, dashGridOptions={"domLayout": "print"}, ) latin_text = dcc.Markdown(""" ### Latin Text Lorem ipsum dolor sit amet, ne cum repudiare abhorreant. Atqui molestiae neglegentur ad nam, mei amet eros ea, populo deleniti scaevola et pri. Pro no ubique explicari, his reque nulla consequuntur in. His soleat doctus constituam te, sed at alterum repudiandae. Suas ludus electram te ius. """, style={"maxWidth": 800}) more_latin_text = dcc.Markdown(""" ### More Latin Text Lorem ipsum dolor sit amet, ne cum repudiare abhorreant. Atqui molestiae neglegentur ad nam, mei amet eros ea, populo deleniti scaevola et pri. Pro no ubique explicari, his reque nulla consequuntur in. His soleat doctus constituam te, sed at alterum repudiandae. Suas ludus electram te ius. """, style={"maxWidth": 800}) print_layout = html.Div( [ dbc.ModalHeader(dbc.Button("Print", id="grid-browser-print-btn")), dbc.ModalBody( # customize your printed report here [ html.H1("Dash AG Grid Print Report Demo", className="py-4"), latin_text, print_grid, more_latin_text, ], id="grid-print-area", ), html.Div(id="dummy"), ] ) app.layout = html.Div( [ dbc.Button("Print Report", id="grid-modal-print-btn"), grid, latin_text, dbc.Modal( print_layout, id="modal-print-container", is_open=False, size='xl' ), ], style={"margin": 20}, ) @callback( Output("grid-modal-print", "columnState"), Output("grid-modal-print", "filterModel"), Output("modal-print-container", "is_open"), Input("grid-modal-print-btn", "n_clicks"), State("grid-regular-layout", "columnState"), State("grid-regular-layout", "filterModel"), prevent_initial_call=True, ) def open_print_modal(_, col_state, filter_model): return col_state, filter_model, True app.clientside_callback( """ function () { var printContents = document.getElementById('grid-print-area').innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; location.reload() return window.dash_clientside.no_update } """, Output("dummy", "children"), Input("grid-browser-print-btn", "n_clicks"), prevent_initial_call=True, ) if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Simple Example with ALL and State Source: https://dash.plotly.com/pattern-matching-callbacks.md This example dynamically adds dcc.Dropdown components and displays their selected values. It uses the ALL selector and State to manage the list of dropdowns. ```python from dash import Dash, dcc, html, Input, Output, State, ALL, callback app = Dash(__name__, suppress_callback_exceptions=True) app.layout = html.Div([ html.Button("Add Filter", id="add-filter", n_clicks=0), html.Div(id='dropdown-container', children=[]), html.Div(id='dropdown-container-output') ]) @callback( Output('dropdown-container', 'children'), Input('add-filter', 'n_clicks'), State('dropdown-container', 'children')) def display_dropdowns(n_clicks, children): new_dropdown = dcc.Dropdown( ['NYC', 'MTL', 'LA', 'TOKYO'], id={ 'type': 'filter-dropdown', 'index': n_clicks } ) children.append(new_dropdown) return children @callback( Output('dropdown-container-output', 'children'), Input({'type': 'filter-dropdown', 'index': ALL}, 'value') ) def display_output(values): return html.Div([ html.Div('Dropdown {} = {}'.format(i + 1, value)) for (i, value) in enumerate(values) ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Install Specific .deb Files Source: https://dash.plotly.com/dash-enterprise/application-structure/django-app.md Includes links to specific .deb files for installation. Useful for packages not available in standard repositories. ```html https://downloads.example.com/example.deb ``` -------------------------------- ### Cytoscape Circle Layout Example Source: https://dash.plotly.com/cytoscape/layout.md Use this snippet to display a Cytoscape graph with nodes arranged in a circular layout. Ensure dash_cytoscape is installed and imported. ```python from dash import Dash, html import dash_cytoscape as cyto app = Dash() nodes = [ { 'data': {'id': short, 'label': label}, 'position': {'x': 20 * lat, 'y': -20 * long} } for short, label, long, lat in ( ('la', 'Los Angeles', 34.03, -118.25), ('nyc', 'New York', 40.71, -74), ('to', 'Toronto', 43.65, -79.38), ('mtl', 'Montreal', 45.50, -73.57), ('van', 'Vancouver', 49.28, -123.12), ('chi', 'Chicago', 41.88, -87.63), ('bos', 'Boston', 42.36, -71.06), ('hou', 'Houston', 29.76, -95.37) ) ] edges = [ {'data': {'source': source, 'target': target}} for source, target in ( ('van', 'la'), ('la', 'chi'), ('hou', 'chi'), ('to', 'mtl'), ('mtl', 'bos'), ('nyc', 'bos'), ('to', 'hou'), ('to', 'nyc'), ('la', 'nyc'), ('nyc', 'bos') ) ] elements = nodes + edges app.layout = html.Div([ cyto.Cytoscape( id='cytoscape-layout-2', elements=elements, style={'width': '100%', 'height': '350px'}, layout={ 'name': 'circle' } ) ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Checklist with Options and Value as Keyword Arguments Source: https://dash.plotly.com/dash-core-components/checklist.md Demonstrates setting checklist options and values using keyword arguments. Options are provided as a list of strings. ```python dcc.Checklist( options=['New York City', 'Montreal', 'San Francisco'], value=['Montreal'] ) ``` -------------------------------- ### Default Igv Component Source: https://dash.plotly.com/dash-bio/igv.md A basic example of the Igv component without any additional properties. This snippet demonstrates the initial setup for a default Igv visualization. ```python from dash import Dash, html, dcc, Input, Output, callback import dash_bio as dashbio app = Dash() HOSTED_GENOME_DICT = [ {'value': 'mm10', 'label': 'Mouse (GRCm38/mm10)'}, {'value': 'rn6', 'label': 'Rat (RGCS 6.0/rn6)'}, {'value': 'gorGor4', 'label': 'Gorilla (gorGor4.1/gorGor4)'}, {'value': 'panTro4', 'label': 'Chimp (SAC 2.1.4/panTro4)'}, {'value': 'panPan2', 'label': 'Bonobo (MPI-EVA panpan1.1/panPan2)'}, {'value': 'canFam3', 'label': 'Dog (Broad CanFam3.1/canFam3)'}, {'value': 'ce11', 'label': 'C. elegans (ce11)'} ] app.layout = html.Div([ dcc.Loading(id='default-igv-container'), html.Hr(), html.P('Select the genome to display below.'), dcc.Dropdown( id='default-igv-genome-select', options=HOSTED_GENOME_DICT, value='ce11' ) ]) # Return the IGV component with the selected genome. @callback( Output('default-igv-container', 'children'), Input('default-igv-genome-select', 'value') ) def return_igv(genome): return html.Div([ dashbio.Igv( id='default-igv', genome=genome, minimumBases=100, ) ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Update Grid API Usage for Column API Removal Source: https://dash.plotly.com/dash-ag-grid/migration-guide.md Replace calls to the deprecated Column API with the Grid API. This example shows how to get all displayed columns. ```javascript dagfuncs.isFirstColumn = function(params) { var displayedColumns = params.api.getAllDisplayedColumns(); var thisIsFirstColumn = displayedColumns[0] === params.column; return thisIsFirstColumn; } ``` -------------------------------- ### Simple Example with ALL and Partial Updates Source: https://dash.plotly.com/pattern-matching-callbacks.md This example demonstrates how to dynamically add dcc.Dropdown components and update a display based on their values using the ALL selector and partial property updates with Patch. It requires Dash 2.9 or later. ```python from dash import Dash, dcc, html, Input, Output, ALL, Patch, callback app = Dash() app.layout = html.Div( [ html.Button("Add Filter", id="add-filter-btn", n_clicks=0), html.Div(id="dropdown-container-div", children=[]), html.Div(id="dropdown-container-output-div"), ] ) @callback( Output("dropdown-container-div", "children"), Input("add-filter-btn", "n_clicks") ) def display_dropdowns(n_clicks): patched_children = Patch() new_dropdown = dcc.Dropdown( ["NYC", "MTL", "LA", "TOKYO"], id={"type": "city-filter-dropdown", "index": n_clicks}, ) patched_children.append(new_dropdown) return patched_children @callback( Output("dropdown-container-output-div", "children"), Input({"type": "city-filter-dropdown", "index": ALL}, "value"), ) def display_output(values): return html.Div( [html.Div(f"Dropdown {i + 1} = {value}") for (i, value) in enumerate(values)] ) if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Basic Auth Installation Source: https://dash.plotly.com/authentication.md Install the necessary Dash and dash-auth packages for basic HTTP authentication. Ensure you are using compatible versions. ```bash pip install dash==4.3.0rc0 pip install dash-auth==2.0.0 ``` -------------------------------- ### DataTable with Callbacks and Bootstrap Theme Source: https://dash.plotly.com/datatable.md Integrate DataTable with callbacks to display active cell information. This example uses Dash Bootstrap Components for styling. Ensure 'dash-bootstrap-components' is installed. ```python from dash import Dash, Input, Output, callback, dash_table import pandas as pd import dash_bootstrap_components as dbc df = pd.read_csv('https://git.io/Juf1t') app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = dbc.Container([ dbc.Label('Click a cell in the table:'), dash_table.DataTable(df.to_dict('records'),[{"name": i, "id": i} for i in df.columns], id='tbl'), dbc.Alert(id='tbl_out'), ]) @callback(Output('tbl_out', 'children'), Input('tbl', 'active_cell')) def update_graphs(active_cell): return str(active_cell) if active_cell else "Click the table" if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Circos Heatmap Example Source: https://dash.plotly.com/dash-bio/circos.md Demonstrates how to create a heatmap track on a Circos plot. Requires 'json' and 'urllib.request' for data fetching. The data should be in a list of dictionaries, each with 'block_id', 'start', 'end', and 'value'. ```python import json import urllib.request as urlreq import dash_bio as dashbio data = urlreq.urlopen( "https://git.io/circos_graph_data.json" ).read().decode("utf-8") circos_graph_data = json.loads(data) layout_config = { "labels": {"display": False}, "ticks": { "color": "#4d4d4d", "labelColor": "#4d4d4d", "spacing": 10000000, "labelSuffix": "Mb", "labelDenominator": 1000000, "labelSize": 10, }, } heatmap_config = {"innerRadius": 250, "outerRadius": 300, "color": "Greens"} dashbio.Circos( layout=circos_graph_data["GRCh37"], config=layout_config, tracks=[ { "type": "HEATMAP", "data": circos_graph_data["histogram"], "config": heatmap_config, } ], ) ``` -------------------------------- ### Initialize App with External Stylesheets Source: https://dash.plotly.com/tutorial.md Sets up the Dash app and applies external CSS stylesheets for enhanced visual presentation. Includes data loading and component definitions. ```python # Import packages from dash import Dash, html, dcc, callback, Output, Input import dash_ag_grid as dag import pandas as pd import plotly.express as px # Incorporate data df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv') # Initialize the app - incorporate css external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = Dash(external_stylesheets=external_stylesheets) # App layout app.layout = [ html.Div(className='row', children='My First App with Data, Graph, and Controls', style={'textAlign': 'center', 'color': 'blue', 'fontSize': 30}), html.Div(className='row', children=[ dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'], value='lifeExp', inline=True, id='my-radio-buttons-final') ]), html.Div(className='row', children=[ html.Div(className='six columns', children=[ dag.AgGrid( rowData=df.to_dict('records'), columnDefs=[{"field": i} for i in df.columns] ) ]), html.Div(className='six columns', children=[ dcc.Graph(figure={}, id='histo-chart-final') ]) ]) ] ``` -------------------------------- ### Bounds & Selection Stream Example with HoloViews and Dash Source: https://dash.plotly.com/holoviews.md Demonstrates using Bounds and Selection1D streams together to create interactive visualizations in Dash. Requires importing Dash, holoviews, and streams. ```python from dash import Dash, html import numpy as np import holoviews as hv from holoviews import streams from holoviews.plotting.plotly.dash import to_dash # Declare distribution of Points points = hv.Points( np.random.multivariate_normal((0, 0), [[1, 0.1], [0.1, 1]], (1000,)) ) # Declare points selection sel = streams.Selection1D(source=points) # Declare DynamicMap computing mean y-value of selection mean_sel = hv.DynamicMap( lambda index: hv.HLine(points['y'][index].mean() if index else -10), kdims=[], streams=[sel] ) # Declare a Bounds stream and DynamicMap to get box_select geometry and draw it box = streams.BoundsXY(source=points, bounds=(0,0,0,0)) bounds = hv.DynamicMap(lambda bounds: hv.Bounds(bounds), streams=[box]) # Declare DynamicMap to apply bounds selection dmap = hv.DynamicMap(lambda bounds: points.select(x=(bounds[0], bounds[2]), y=(bounds[1], bounds[3])), streams=[box]) # Compute histograms of selection along x-axis and y-axis yhist = hv.operation.histogram( dmap, bin_range=points.range('y'), dimension='y', dynamic=True, normed=False ) xhist = hv.operation.histogram( dmap, bin_range=points.range('x'), dimension='x', dynamic=True, normed=False ) # Combine components and display layout = points * mean_sel * bounds << yhist << xhist # Create App app = Dash() components = to_dash( app, [layout], reset_button=True, use_ranges=False, ) app.layout = html.Div(components.children) if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Install Dash Enterprise Libraries Source: https://dash.plotly.com/ai-coding-assistants Install the Dash Enterprise client libraries, which include the deployment CLI. Ensure you replace the placeholder with your organization's specific Dash Enterprise URL. ```bash pip install dash-enterprise-libraries --extra-index-url /packages ``` -------------------------------- ### Static Layout on Page Load (String) Source: https://dash.plotly.com/live-updates.md This example demonstrates serving a static layout on page load by setting app.layout to a string. The content, including the current time, is determined only when the app starts. ```python import datetime import dash from dash import html app.layout = html.H1('The time is: ' + str(datetime.datetime.now())) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Capturing Clicks with n_clicks Source: https://dash.plotly.com/dash-html-components.md This example demonstrates how to capture and display the number of times an html.Div element is clicked using the n_clicks property and a Dash callback. Ensure you have Dash installed and the necessary imports. ```python from dash import Dash, html, Input, Output, callback app = Dash() app.layout = html.Div( [ html.Div( "Div with n_clicks event listener", id="click-div", style={"color": "red", "font-weight": "bold"}, ), html.P(id="click-output"), ] ) @callback( Output("click-output", "children"), Input("click-div", "n_clicks") ) def click_counter(n_clicks): return f"The html.Div above has been clicked this many times: {n_clicks}" app.run(debug=True) ``` -------------------------------- ### Set Up Dash App with Controls and Callbacks Source: https://dash.plotly.com/tutorial.md Initializes a Dash app with a title, radio button controls, an AG Grid table, and a graph component. It imports necessary modules for callbacks, including Output and Input. ```python # Import packages from dash import Dash, html, dcc, callback, Output, Input import dash_ag_grid as dag import pandas as pd import plotly.express as px # Incorporate data df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv') # Initialize the app app = Dash() # App layout app.layout = [ html.Div(children='My First App with Data, Graph, and Controls'), html.Hr(), dcc.RadioItems(options=['pop', 'lifeExp', 'gdpPercap'], value='lifeExp', id='controls-and-radio-item'), dag.AgGrid( rowData=df.to_dict('records'), columnDefs=[{"field": i} for i in df.columns] ), dcc.Graph(figure={}, id='controls-and-graph') ] ``` -------------------------------- ### Cytoscape Grid Layout Example Source: https://dash.plotly.com/cytoscape/layout.md Use this snippet to display a Cytoscape graph with nodes arranged in a grid layout. This is useful for visualizing hierarchical or structured data. Ensure dash_cytoscape is installed and imported. ```python from dash import Dash, html import dash_cytoscape as cyto app = Dash() nodes = [ { 'data': {'id': short, 'label': label}, 'position': {'x': 20 * lat, 'y': -20 * long} } for short, label, long, lat in ( ('la', 'Los Angeles', 34.03, -118.25), ('nyc', 'New York', 40.71, -74), ('to', 'Toronto', 43.65, -79.38), ('mtl', 'Montreal', 45.50, -73.57), ('van', 'Vancouver', 49.28, -123.12), ('chi', 'Chicago', 41.88, -87.63), ('bos', 'Boston', 42.36, -71.06), ('hou', 'Houston', 29.76, -95.37) ) ] edges = [ {'data': {'source': source, 'target': target}} for source, target in ( ('van', 'la'), ('la', 'chi'), ('hou', 'chi'), ('to', 'mtl'), ('mtl', 'bos'), ('nyc', 'bos'), ('to', 'hou'), ('to', 'nyc'), ('la', 'nyc'), ('nyc', 'bos') ) ] elements = nodes + edges app.layout = html.Div([ cyto.Cytoscape( id='cytoscape-layout-3', elements=elements, style={'width': '100%', 'height': '350px'}, layout={ 'name': 'grid' } ) ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Basic Multi-Page App Structure Source: https://dash.plotly.com/urls.md Sets up a simple multi-page application. The callback displays the current URL pathname. Use dcc.Link for client-side navigation. ```python from dash import Dash, dcc, html, callback, Input, Output app = Dash() app.layout = html.Div([ # represents the browser address bar and doesn't render anything dcc.Location(id='url', refresh=False), dcc.Link('Navigate to "/"', href='/'), html.Br(), dcc.Link('Navigate to "/page-2"', href='/page-2'), # content will be rendered in this element html.Div(id='page-content') ]) @callback(Output('page-content', 'children'), Input('url', 'pathname')) def display_page(pathname): return html.Div([ html.H3(f'You are on page {pathname}') ]) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Circos Histogram Example Source: https://dash.plotly.com/dash-bio/circos.md Illustrates the creation of a histogram track for a Circos plot. The data format is similar to the heatmap, requiring 'block_id', 'start', 'end', and 'value'. Configuration options control the appearance and scale of the histogram. ```python import json import urllib.request as urlreq import dash_bio as dashbio data = urlreq.urlopen( "https://git.io/circos_graph_data.json" ).read().decode("utf-8") circos_graph_data = json.loads(data) layout_config = { "labels": { "size": 10, "color": "#4d4d4d", }, "ticks": {"display": False}, } tracks_config = {"innerRadius": 300, "outerRadius": 400, "color": "OrRd"} dashbio.Circos( layout=circos_graph_data["GRCh37"], config=layout_config, tracks=[ { "type": "HISTOGRAM", "data": circos_graph_data["histogram"], "config": tracks_config, } ], ) ``` -------------------------------- ### Basic DataTable Setup Source: https://dash.plotly.com/datatable/interactivity.md This snippet shows the basic structure for creating a Dash DataTable. It includes importing necessary libraries and setting up the app layout. ```python from dash import Dash, dash_table, html app = Dash(__name__) app.layout = html.Div([ dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), ) ]) if __name__ == '__main__' app.run_server(debug=True) ``` -------------------------------- ### Plugin Initialization with Hooks Source: https://dash.plotly.com/dash-plugins-using-hooks.md Example of a plugin's `__init__.py` file that defines layout, callback, and error hooks for automatic registration. Hooks are defined outside of functions for immediate execution. ```python from dash import html, hooks, set_props, Input, Output def generate_error_notification(): return [ html.Div( [ html.Div( [ html.Span( "Callback errors will display here.", id="error-text", ), html.Button( "×", id="dismiss-button", style={ "position": "absolute", "top": "5px", "right": "10px", }, ), ], style={ "padding": "15px", "border": "1px solid #f5c6cb", }, ) ], id="callback-error-banner-wrapper", ) ] @hooks.layout() def update_layout(layout): return generate_error_notification() + ( layout if isinstance(layout, list) else [layout] ) @hooks.callback( Output("callback-error-banner-wrapper", "style"), Input("dismiss-button", "n_clicks"), prevent_initial_call=True, ) def hide_banner(n_clicks): if n_clicks: return dict(display="none") @hooks.error() def on_error(err): set_props("callback-error-banner-wrapper", dict(style=dict(display="block"))) set_props("error-text", dict(children=f"The error is: {err}")) ``` -------------------------------- ### Circos Highlight Example Source: https://dash.plotly.com/dash-bio/circos.md Shows how to add a highlight track to a Circos plot. This track is useful for emphasizing specific regions. The data format requires 'block_id', 'start', 'end', and a color key (e.g., 'gieStain') for styling. ```python import json import urllib.request as urlreq import dash_bio as dashbio data = urlreq.urlopen( "https://git.io/circos_graph_data.json" ).read().decode("utf-8") circos_graph_data = json.loads(data) layout_config = { "labels": {"display": False}, "ticks": { "color": "#4d4d4d", "labelColor": "#4d4d4d", "spacing": 10000000, "labelSuffix": "Mb", "labelDenominator": 1000000, "labelSize": 10, }, } highlight_config = { "innerRadius": 250, "outerRadius": 300, "color": {"name": "gieStain"}, } dashbio.Circos( layout=circos_graph_data["GRCh37"], config=layout_config, tracks=[ { "type": "HIGHLIGHT", "data": circos_graph_data["cytobands"], "config": highlight_config, } ], ) ``` -------------------------------- ### Basic AG Grid Enterprise Setup Source: https://dash.plotly.com/dash-ag-grid/enterprise-ag-grid.md To use an AG Grid Enterprise key with Dash AG Grid, set `enableEnterpriseModules=True` and include your license key with `licenseKey=`. ```python dag.AgGrid( enableEnterpriseModules=True, licenseKey=, columnDefs=ColumnDefs, rowData=rowData ) ``` -------------------------------- ### Dash AG Grid Example with Case-Sensitive Set Filter Source: https://dash.plotly.com/dash-ag-grid/enterprise-set-filter-list.md A complete Dash application demonstrating the AG Grid Set Filter with both case-insensitive and case-sensitive columns. Includes row data, column definitions, and grid setup. ```python from dash import Dash, html import dash_ag_grid as dag import os rowData = [ {"colour": "Black"}, {"colour": "BLACK"}, {"colour": "black"}, {"colour": "Red"}, {"colour": "RED"}, {"colour": "red"}, {"colour": "Orange"}, {"colour": "ORANGE"}, {"colour": "orange"}, {"colour": "White"}, {"colour": "WHITE"}, {"colour": "white"}, {"colour": "Yellow"}, {"colour": "YELLOW"}, {"colour": "yellow"}, {"colour": "Green"}, {"colour": "GREEN"}, {"colour": "green"}, {"colour": "Purple"}, {"colour": "PURPLE"}, {"colour": "purple"}, ] app = Dash() columnDefs = [ { "headerName": "Case Insensitive (default)", "field": "colour", "filter": "agSetColumnFilter", "filterParams": { "caseSensitive": False, "cellRenderer": "ColourCellRenderer", }, }, { "headerName": "Case Sensitive", "field": "colour", "filter": "agSetColumnFilter", "filterParams": { "caseSensitive": True, "cellRenderer": "ColourCellRenderer", }, }, ] defaultColDef = { "flex": 1, "minWidth": 225, "cellRenderer": "ColourCellRenderer", "floatingFilter": True, } grid = dag.AgGrid( id="set-filters-case-sensitive", # Set filter is an AG Grid Enterprise feature. # A license key should be provided if it is used. # License keys can be passed to the `licenseKey` argument of dag.AgGrid enableEnterpriseModules=True, licenseKey=os.environ['AGGRID_ENTERPRISE'], rowData=rowData, columnDefs=columnDefs, defaultColDef=defaultColDef, dashGridOptions={"sideBar": "filters"}, ) app.layout = html.Div([html.H4("Set Filter Example - case sensitive filtering"), grid]) if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Basic dcc.Loading Example Source: https://dash.plotly.com/dash-core-components/loading.md Demonstrates basic usage with default and custom spinner types. Shows how nested children also trigger the loading state. ```Python from dash import Dash, dcc, html, Input, Output, callback import time app = Dash() app.layout = html.Div([ html.H3("Edit text input to see loading state"), html.Div("Input triggers local spinner"), dcc.Input(id="loading-input-1"), dcc.Loading( id="loading-1", type="default", children=html.Div(id="loading-output-1") ), html.Div([ html.Div('Input triggers nested spinner'), dcc.Input(id="loading-input-2"), dcc.Loading( id="loading-2", children=[html.Div([html.Div(id="loading-output-2")])], type="circle", ) ]), ]) @callback(Output("loading-output-1", "children"), Input("loading-input-1", "value")) def input_triggers_spinner(value): time.sleep(1) return value @callback(Output("loading-output-2", "children"), Input("loading-input-2", "value")) def input_triggers_nested(value): time.sleep(1) return value if __name__ == "__main__": app.run(debug=False) ```