### Setup Tests Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Builds and installs components required for running tests. Supports both Python and R test setups. ```bash npm run setup-tests.py ``` ```bash npm run setup-tests.R ``` -------------------------------- ### Install Module Locally Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/README.md Generates metadata and builds the JavaScript bundle for local installation. After this, subsequent changes can be installed with `python setup.py install` if `npm run build:watch` is running. ```bash npm run install-local ``` -------------------------------- ### Bar Chart Example Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Illustrates the creation of a simple bar chart. Ensure Plotly is installed. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Bar( x=['A', 'B', 'C', 'D'], y=[10, 15, 7, 12] )) fig.update_layout( title='Simple Bar Chart', xaxis_title='Category', yaxis_title='Value' ) fig.show() ``` -------------------------------- ### Install and activate Node.js with nvm Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Commands to install the latest Node.js version and activate the environment. Admin access is required for the activation step. ```bash nvm install latest ``` ```bash nvm use latest ``` -------------------------------- ### Install Dash Source: https://github.com/plotly/dash/blob/dev/components/dash-table/README.md Command to install the Dash library via pip. ```bash pip install dash ``` -------------------------------- ### Simple DatePickerRange Example with Callback Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html A basic example demonstrating the DatePickerRange component integrated with a Dash callback to display selected dates. Configure min/max allowed dates and the initially visible month. ```R library(dashHtmlComponents) library(dash) app = Dash$new() app$layout( htmlDiv( list( dccDatePickerRange( id='my-date-picker-single', min_date_allowed=as.Date('1995-8-5'), max_date_allowed=as.Date('2017-9-19'), initial_visible_month=as.Date('2017-8-5'), end_date = as.Date('2017-8-5') ), htmlDiv(id='output-container-date-picker-range') ) ) ) app$callback( output = list(id='output-container-date-picker-range', property = 'children'), params = list(input(id = 'my-date-picker-range', property = 'start_date'), input(id = 'my-date-picker-range', property = 'end_date')), function(start_date, end_date){ string_prefix = 'You have selected: ' if(is.null(start_date) == FALSE){ start_date = format(as.Date(start_date), format = '%B %d,%Y') string_prefix = paste(string_prefix, 'Start Date ', start_date, sep = "") } if(is.null(end_date) == FALSE){ end_date = format(as.Date(end_date), format = '%B %d,%Y') string_prefix = paste(string_prefix, 'End Date: ', end_date, sep = "") } if(nchar(string_prefix) == nchar('You have selected: ')){ return('Select a date to see it displayed here') } else{ return(string_prefix) } } ) app$run_server() ``` -------------------------------- ### Verify Node.js and npm installation Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Check that Node.js and npm are correctly installed and accessible in your terminal. ```bash node -v npm -v ``` -------------------------------- ### Basic RangeSlider with Callback Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html A simple RangeSlider example demonstrating how to tie it to a callback to display the selected range. Ensure the 'dash' library is installed. ```R library(dash) app <- Dash$new() app$layout( htmlDiv( list( dccRangeSlider( id='my-range-slider', min=0, max=20, step=0.5, value=list(5, 15) ), htmlDiv(id='output-container-range-slider') ) ) ) app$callback( output(id = 'output-container-range-slider', property='children'), params=list(input(id='my-range-slider', property='value')), function(value) { sprintf('You have selected [%0.1f, %0.1f]', value[1], value[2]) }) app$run_server() ``` -------------------------------- ### Install Dash and Dependencies Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Installs Dash and its development/testing dependencies using pip. For some shells, you may need to escape the square brackets. ```bash pip install -e .[ci,dev,testing,celery,diskcache] ``` ```bash npm ci ``` -------------------------------- ### Verify Dash Installation Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Checks if the Dash installation was successful by listing installed packages and filtering for those starting with 'dash'. ```bash pip list | grep dash ``` -------------------------------- ### Install Dash with Development Dependencies Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/README.md Install the dash package with development and testing dependencies to enable local development of core components. Ensure you are using a virtual environment and Python 3. ```bash python -m venv venv && . venv/bin/activate ``` ```bash pip install -e .[dev,testing] ``` ```bash npm ci && npm run build ``` ```bash pip install -e . ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/README.md Installs Python packages required for building components. Ensure you have a virtual environment activated. ```bash pip install -r dev-requirements.txt ``` -------------------------------- ### Display Uploaded Images Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html This example shows how to handle image file uploads and display them directly in the app using the htmlImg component. ```R library(dashHtmlComponents) library(dash) library(anytime) app = Dash$new() app$layout(htmlDiv(list( dccUpload( id='upload-image', children=htmlDiv(list( 'Drag and Drop or ', htmlA('Select Files') )), style=list( 'width'= '100%', 'height'= '60px', 'lineHeight'= '60px', 'borderWidth'= '1px', 'borderStyle'= 'dashed', 'borderRadius'= '5px', 'textAlign'= 'center', 'margin'= '10px' ), # Allow multiple files to be uploaded multiple=TRUE ), htmlDiv(id='output-image-upload') ))) parse_content = function(contents, filename, date){ return(htmlDiv(list( htmlH5(filename), htmlH6(anytime(date)), htmlImg(src=contents), htmlHr(), htmlDiv('Raw Content'), htmlPre(paste(substr(toJSON(contents), 1, 100), "..."), style=list( 'whiteSpace'= 'pre-wrap', 'wordBreak'= 'break-all' )) ))) } app$callback( output = list(id='output-image-upload', property = 'children'), params = list(input(id = 'upload-image', property = 'contents'), state(id = 'upload-image', property = 'filename'), state(id = 'upload-image', property = 'last_modified')), function(list_of_contents, list_of_names, list_of_dates){ if(is.null(list_of_contents) == FALSE){ children = lapply(1:length(list_of_contents), function(x){ parse_content(list_of_contents[[x]], list_of_names[[x]], list_of_dates[[x]]) }) } else{ } return(children) } ) app$run_server() ``` -------------------------------- ### Basic Dash App with Callback and Server Run Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html A fundamental example demonstrating a Dash app with a callback function to update content based on tab selection and then running the server. ```r app$callback( output = list(id='tabs-content-props', property = 'children'), params = list(input(id = 'tabs-styled-with-props', property = 'value')), function(tab){ if(tab == 'tab-1'){ return(htmlDiv( list(htmlH3('Tab content 1')) )) } else if(tab == 'tab-2'){ return(htmlDiv( list(htmlH3('Tab content 2')) )) } }) app$run_server() ``` -------------------------------- ### Test Tarball Installation Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/README.md Installs the generated Python tarball in a new environment to test the distribution before publishing. ```bash pip install dash-html-components-.tar.gz ``` -------------------------------- ### Configure DatePickerRange RTL and Week Start Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html Sets the calendar to right-to-left orientation and defines the starting day of the week. ```R dccDatePickerRange( is_RTL = TRUE, first_day_of_week = 3, start_date= format(as.Date("2017-6-21"), format = "%Y,%m,%d") ) ``` -------------------------------- ### Run Dash Development Server Source: https://github.com/plotly/dash/blob/dev/MAKE_A_NEW_BACK_END.md Start the Dash development server to host your application. The '...' indicates that the run_server method accepts various configuration options. ```python app.run_server(...) ``` -------------------------------- ### Creating a Basic Dash App with a Graph Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html A minimal Dash application that displays a Plotly graph. Ensure Dash and Plotly are installed. ```python import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go app = dash.Dash(__name__) # Create a simple Plotly figure fig = go.Figure( data=[ go.Bar(x=['Apples', 'Bananas', 'Cherries'], y=[4, 1, 2]) ], layout=go.Layout( title='My First Dash Plot' ) ) app.layout = html.Div([ html.H1('Dash App with Plotly Graph'), dcc.Graph( id='example-graph', figure=fig ) ]) if __name__ == '__main__': app.run_server(debug=True) ``` -------------------------------- ### Parse and Display CSV or Excel Files Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html This example demonstrates how to process uploaded CSV or Excel files and render the data in a DataTable. ```R library(dashHtmlComponents) library(dash) library(anytime) app = Dash$new() app$layout(htmlDiv(list( dccUpload( id='upload-data', children=htmlDiv(list( 'Drag and Drop or ', htmlA('Select Files') )), style=list( 'width'= '100%', 'height'= '60px', 'lineHeight'= '60px', 'borderWidth'= '1px', 'borderStyle'= 'dashed', 'borderRadius'= '5px', 'textAlign'= 'center', 'margin'= '10px' ), # Allow multiple files to be uploaded multiple=TRUE ), htmlDiv(id='output-data-upload') ))) parse_contents = function(contents, filename, date){ content_type = strsplit(contents, ",") content_string = strsplit(contents, ",") decoded = base64_dec(content_string) if('csv' %in% filename){ df = read.csv(utf8::as_utf8(decoded)) } else if('xls' %in% filename){ df = read.table(decoded, encoding = 'bytes') } else{ return(htmlDiv(list( 'There was an error processing this file.' ))) } return(htmlDiv(list( htmlH5(filename), htmlH6(anytime(date)), dashDataTable(df_to_list('records'),columns = lapply(colnames(df), function(x){list('name' = x, 'id' = x)})), htmlHr(), htmlDiv('Raw Content'), htmlPre(paste(substr(toJSON(contents), 1, 100), "..."), style=list( 'whiteSpace'= 'pre-wrap', 'wordBreak'= 'break-all' )) ))) } app$callback( output = list(id='output-data-upload', property = 'children'), params = list(input(id = 'upload-data', property = 'contents'), state(id = 'upload-data', property = 'filename'), state(id = 'upload-data', property = 'last_modified')), function(list_of_contents, list_of_names, list_of_dates){ if(is.null(list_of_contents) == FALSE){ children = lapply(1:length(list_of_contents), function(x){ parse_content(list_of_contents[[x]], list_of_names[[x]], list_of_dates[[x]]) }) } return(children) }) app$run_server() ``` -------------------------------- ### Basic Scatter Plot with Customization Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Demonstrates creating a scatter plot with custom marker styles and colors. Ensure Plotly is installed. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Scatter( x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode="markers", marker=dict(size=10, color="red", symbol="circle") )) fig.update_layout( title="Basic Scatter Plot", xaxis_title="X Axis", yaxis_title="Y Axis" ) fig.show() ``` -------------------------------- ### Box Plot Visualization Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Demonstrates creating a box plot to show data distribution and outliers. Ensure Plotly is installed. ```python import plotly.graph_objects as go import numpy as np # Sample data for box plot x_data = ['Group A', 'Group B', 'Group C'] y_data = [ np.random.randn(50) + 2, np.random.randn(50) + 3, np.random.randn(50) + 1.5 ] fig = go.Figure(data=go.Box( y=y_data, x=x_data, name='Box Plot' )) fig.update_layout( title='Box Plot Example', yaxis_title='Value' ) fig.show() ``` -------------------------------- ### Tabs with Prop-Based Colors Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html This example shows how to set the border, primary, and background colors of Dash Tabs directly through the `colors` prop. All three color properties must be specified if using this prop. ```R library(dashHtmlComponents) library(dash) app = Dash$new() app$layout(htmlDiv(list( dccTabs(id="tabs-styled-with-props", value='tab-1', children=list( dccTab(label='1', value='tab-1'), dccTab(label='2', value='tab-2') ), colors=list( "border"= "white", "primary"= "gold", "background"= "cornsilk" )), htmlDiv(id='tabs-content-props') ))) ) ``` -------------------------------- ### Tabs with Inline Styles Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html This example demonstrates styling Dash Tabs using inline style dictionaries. This approach is useful for dynamic styling or when external CSS is not preferred. ```R library(dashHtmlComponents) library(dash) app = Dash$new() tabs_styles = list( 'height'= '44px' ) tab_style = list( 'borderBottom'= '1px solid #d6d6d6', 'padding'= '6px', 'fontWeight'= 'bold' ) tab_selected_style = list( 'borderTop'= '1px solid #d6d6d6', 'borderBottom'= '1px solid #d6d6d6', 'backgroundColor'= '#119DFF', 'color'= 'white', 'padding'= '6px' ) app$layout(htmlDiv(list( dccTabs(id="tabs-styled-with-inline", value='tab-1', children=list( dccTab(label='Tab 1', value='tab-1', style=tab_style, selected_style=tab_selected_style), dccTab(label='Tab 2', value='tab-2', style=tab_style, selected_style=tab_selected_style), dccTab(label='Tab 3', value='tab-3', style=tab_style, selected_style=tab_selected_style), dccTab(label='Tab 4', value='tab-4', style=tab_style, selected_style=tab_selected_style) ), style=tabs_styles), htmlDiv(id='tabs-content-inline') ))) app$callback( output = list(id='tabs-content-inline', property = 'children'), params = list(input(id = 'tabs-styled-with-inline', property = 'value')), function(tab){ if(tab == 'tab-1'){ return(htmlDiv( list(htmlH3('Tab content 1')) )) } else if(tab == 'tab-2'){ return(htmlDiv( list(htmlH3('Tab content 2')) )) } else if(tab == 'tab-3'){ return(htmlDiv( list(htmlH3('Tab content 3')) )) } else if(tab == 'tab-4'){ return(htmlDiv( list(htmlH3('Tab content 4')) )) } } ) app$run_server() ``` -------------------------------- ### DatePickerSingle Month Format Examples Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html Shows how to configure the `month_format` property for the DatePickerSingle component to alter the display of calendar headers. Uses various string tokens for formatting. ```R dccDatePickerSingle( month_format="MMM Do, YY", placeholder="MMM Do, YY", date=format(as.Date("2017-6-21"), format = "%Y,%m,%d") ) ``` ```R dccDatePickerSingle( month_format="M-D-Y-Q", placeholder="M-D-Y-Q", date=format(as.Date("2017-6-21"), format = "%Y,%m,%d") ) ``` ```R dccDatePickerSingle( month_format="MMMM Y", placeholder="MMMM Y", date=format(as.Date("2020-2-29"), format = "%Y,%m,%d") ) ``` -------------------------------- ### DatePickerSingle Display Format Examples Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html Illustrates different `display_format` options for the DatePickerSingle component using various string tokens. The format determines how the selected date is shown. ```R dccDatePickerSingle( date="2017-06-21", display_format="MMM Do, YY" ) ``` ```R dccDatePickerSingle( date=format(as.Date("2017-6-21"), format = "%Y,%m,%d"), display_format="M-D-Y-Q" ) ``` ```R dccDatePickerSingle( date=format(as.Date("2017-6-21"), format = "%Y,%m,%d"), display_format="MMMM Y, DD" ) ``` ```R dccDatePickerSingle( date=format(as.Date("2017-6-21"), format = "%Y,%m,%d"), display_format="X" ) ``` -------------------------------- ### Tabs with Custom CSS Classes Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html This example shows how to apply custom CSS classes to Dash Tabs for styling. Ensure the CSS file is placed in the 'assets' folder. ```R app$callback( output = list(id='tabs-content-classes', property = 'children'), params = list(input(id = 'tabs-with-classes', property = 'value')), function(tab){ if(tab == 'tab-1'){ return(htmlDiv( list(htmlH3('Tab content 1')) )) } else if(tab == 'tab-2'){ return(htmlDiv( list(htmlH3('Tab content 2')) )) } else if(tab == 'tab-3'){ return(htmlDiv( list(htmlH3('Tab content 3')) )) } else if(tab == 'tab-4'){ return(htmlDiv( list(htmlH3('Tab content 4')) )) } } ) app$run_server() ``` ```CSS .custom-tabs-container { width: 85%; } .custom-tabs { border-top-left-radius: 3px; background-color: #f9f9f9; padding: 0px 24px; border-bottom: 1px solid #d6d6d6; } .custom-tab { color:#586069; border-top-left-radius: 3px; border-top: 3px solid transparent !important; border-left: 0px !important; border-right: 0px !important; border-bottom: 0px !important; background-color: #fafbfc; padding: 12px !important; font-family: "system-ui"; display: flex !important; align-items: center; justify-content: center; } .custom-tab--selected { color: black; box-shadow: 1px 1px 0px white; border-left: 1px solid lightgrey !important; border-right: 1px solid lightgrey !important; border-top: 3px solid #e36209 !important; } ``` -------------------------------- ### Store Data with dccStore Component Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html Demonstrates the dccStore component for persisting data in the visitor's browser. This example shows how to initialize the store with data and mentions the different storage types ('memory', 'local', 'session'). ```r library(dash) store <- dccStore(id = "my-store", data = list("my-data" = "data")) ``` -------------------------------- ### Create and Activate Virtual Environment (Linux/Mac) Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Use these commands to create a virtual environment and activate it on Linux or Mac systems. This isolates project dependencies. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Initialize Dash App Source: https://github.com/plotly/dash/blob/dev/MAKE_A_NEW_BACK_END.md Create a new Dash application instance. The '...' indicates that there are various configuration options available for the constructor. ```python from dash import Dash app = Dash(...) ``` -------------------------------- ### Create and Activate Virtual Environment (Windows) Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Use these commands to create a virtual environment and activate it on Windows systems. This isolates project dependencies. ```bash python -m venv venv source venv/scripts/activate ``` -------------------------------- ### Create Production Build Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/README.md Builds the production-ready JavaScript bundles for the component library. ```bash npm run build ``` -------------------------------- ### jQuery Animation Start and Stop Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Controls the animation interval timer. Starts the interval if there are active timers, and stops it when no timers remain. ```javascript m.fx.start = function() { _a || (_a = setInterval(m.fx.tick, m.fx.interval)); }; m.fx.stop = function() { clearInterval(_a); _a = null; }; ``` -------------------------------- ### jQuery get Method Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html A shorthand for making GET requests. Use this for simple data retrieval. It can handle various response types specified by the dataType parameter. ```javascript m.each(["get", "post"], function(a, b) { m[b] = function(a, c, d, e) { return m.ajax({ url: a, type: b, dataType: e, data: c, success: d }) } }) ``` -------------------------------- ### Get Siblings and Children with jQuery Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Use `siblings()` to get all sibling elements of the current element. `children()` selects only the direct children of each element in the set of matched elements. ```javascript m.fn.siblings=function(a){return m.sibling((a.parentNode||{}).firstChild,a)} ``` ```javascript m.fn.children=function(a){return m.sibling(a.firstChild)} ``` -------------------------------- ### Get Text Content with jQuery Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html The .text() method gets the combined text content of all the matched elements, including their descendants. When setting text, it replaces the content of the matched elements. ```javascript jQuery.fn.extend({ text: function(a) { return V(this, function(a) { return void 0 === a ? jQuery.text(this) : this.empty().append((this[0] && this[0].ownerDocument || y).createTextNode(a)) }, null, a, arguments.length) } }); ``` -------------------------------- ### Tooltip Initialization and Event Handling Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Core logic for initializing tooltips and managing hover/focus states. ```javascript var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()}, ``` -------------------------------- ### Creating a Basic Dash App Layout Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Sets up a minimal Dash application layout with a title and a placeholder for a graph. Requires Dash and Plotly. ```python import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash(__name__) app.layout = html.Div([ html.H1('Dash Plotting Example'), dcc.Graph(id='example-graph') ]) if __name__ == '__main__': app.run_server(debug=True) ``` -------------------------------- ### Find Parent Elements with jQuery Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Use the `parent()` method to get the immediate parent of each element in the set of matched elements. Use `parents()` to get all ancestor elements up to the document root. `parentsUntil()` selects elements up to a specified ancestor. ```javascript m.fn.parent=function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null} ``` ```javascript m.fn.parents=function(a){return m.dir(a,"parentNode")} ``` ```javascript m.fn.parentsUntil=function(a,b,c){return m.dir(a,"parentNode",c)} ``` -------------------------------- ### Histogram Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Generates a basic histogram using Plotly. Ensure Plotly is installed. ```python import plotly.graph_objects as go import numpy as np data = np.random.randn(100) fig = go.Figure(data=go.Histogram( x=data )) fig.show() ``` -------------------------------- ### Create a basic Dash slider with callback Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html Initializes a Dash application with a slider component and a callback to display the selected value. ```R library(dash) app <- Dash$new() app$layout( htmlDiv( list( dccSlider( id='my-slider', min=0, max=20, step=0.5, value=10 ), htmlDiv(id='slider-output-container') ) ) ) app$callback( output(id = 'slider-output-container', property = 'children'), params=list(input(id = 'my-slider', property = 'value')), function(value) { sprintf("you have selected %0.1f", value) }) app$run_server() ``` -------------------------------- ### Test Components in Dash Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/README.md To test your components, first run the build watcher with 'npm run build:watch', then run your Dash layout Python script. This requires importing dash_core_components. ```bash npm run build:watch ``` ```python # Import dash_core_components to your layout, then run it: $ python my_dash_layout.py ``` -------------------------------- ### Uninstall Python Package Locally Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/README.md Removes the locally installed dash-html-components package. ```bash npm run uninstall-local ``` -------------------------------- ### Bar Chart Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Generates a simple bar chart using Plotly. Ensure Plotly is installed. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Bar( x=['A', 'B', 'C', 'D'], y=[10, 15, 7, 12] )) fig.show() ``` -------------------------------- ### Pie Chart Creation Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Demonstrates how to generate a pie chart. Plotly library is required. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Pie( labels=['Label 1', 'Label 2', 'Label 3', 'Label 4'], values=[450, 250, 150, 50], hole=.3 # Creates a donut chart )) fig.update_layout( title='Pie Chart Example' ) fig.show() ``` -------------------------------- ### Basic Scatter Plot Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Generates a simple scatter plot using Plotly. Ensure Plotly is installed. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Scatter( x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode='markers' )) fig.show() ``` -------------------------------- ### Adding Annotations to a Plot Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Shows how to add text annotations to a Plotly graph. Ensure Plotly is installed. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Scatter( x=[1, 2, 3, 4], y=[10, 11, 12, 13] )) fig.update_layout( title='Plot with Annotations' ) fig.add_annotation( x=2, # x-coordinate of the annotation y=11, # y-coordinate of the annotation text="Important Point", # Text to display showarrow=True, arrowhead=1 ) fig.show() ``` -------------------------------- ### jQuery FadeTo Method Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Animates the opacity of an element to a specified value. Ensures the element is visible before starting. ```javascript m.fn.fadeTo = function(a, b, c, d) { return this.filter(U).css("opacity", 0).show().end().animate({opacity: b}, a, c, d); }; ``` -------------------------------- ### Build Dash Components (Windows) Source: https://github.com/plotly/dash/blob/dev/CONTRIBUTING.md Builds all Dash component bundles from source code on Windows systems. This uses a specific script that includes extra steps for Windows. ```bash npm run first-build ``` -------------------------------- ### Watch for Component Changes Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/README.md Starts a watcher process to automatically rebuild components when changes are detected during development. ```bash npm run build:watch ``` -------------------------------- ### Basic DatePickerSingle with Callback Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html Demonstrates a basic DatePickerSingle component with min/max date allowed, initial visible month, and a callback to display the selected date. Requires dashHtmlComponents and dash libraries. ```R library(dashHtmlComponents) library(dash) app = Dash$new() app$layout( htmlDiv( list( dccDatePickerSingle( id='my-date-picker-single', min_date_allowed=as.Date('1995-8-5'), max_date_allowed=as.Date('2017-9-19'), initial_visible_month=as.Date('2017-8-5'), date = as.POSIXct("2017-08-25 23:59:59", tz = "GMT") ), htmlDiv(id='output-container-date-picker-single') ) ) ) app$callback( output = list(id='output-container-date-picker-single', property = 'children'), params = list(input(id = 'my-date-picker-single', property = 'date')), function(date){ if(is.null(date) == FALSE){ date = format(as.Date(date), format = '%B %d,%Y') sprintf('You have selected: %s', date) } } ) ``` -------------------------------- ### Tooltip Get UID Method Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Generates a unique ID for the tooltip element, ensuring it does not conflict with existing IDs. ```javascript c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a} ``` -------------------------------- ### Adding Annotations to Plotly Graph Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Shows how to add text annotations with arrows to a Plotly graph. Ensure Plotly is installed. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=[1, 2], y=[2, 1])) fig.update_layout( title='Plot with Annotation' ) fig.add_annotation( x=1, y=2, text='Annotation Text', showarrow=True, arrowhead=1 ) fig.show() ``` -------------------------------- ### Respond.js Initialization and Update Logic Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html This code block contains the core logic for Respond.js, including the update function and the main execution flow. It checks for media query support and, if not available, proceeds to parse and apply styles dynamically. ```javascript function b() { u(!0) } var c = {}; a.respond = c, c.update = function() {}; var d = [], e = function() { var b; try { b = new a.XMLHttpRequest } catch (c) { b = new a.ActiveXObject("Microsoft.XMLHTTP") } return function() { return b } }(); if (c.ajax = f, c.queue = d, c.mediaQueriesSupported = a.matchMedia && null !== a.matchMedia("only all") && a.matchMedia("only all").matches, !c.mediaQueriesSupported) { var g, h, i, j = a.document, k = j.documentElement, l = [], m = [], n = [], o = {}, p = 30, q = j.getElementsByTagName("head") [0] || k, r = j.getElementsByTagName("base")[0], s = q.getElementsByTagName("link"), t = function() { var a, b = j.createElement("div"), c = j.body, d = k.style.fontSize, e = c && c.style.fontSize, f = !1; return b.style.cssText = "position:absolute;font-size:1em;width:1em", c || (c = f = j.createElement("body"), c.style.background = "none"), k.style.fontSize = "100%", c.style.fontSize = "100%", c.appendChild(b), f ? k.removeChild(c) : c.removeChild(b), a = b.offsetWidth, f ? k.removeChild(c) : c.removeChild(b), k.style.fontSize = d, e && (c.style.fontSize = e), a = i = parseFloat(a) }, u = function(b) { var c = "clientWidth", d = k[c], e = "CSS1Compat" === j.compatMode && d || j.body[c] || d, f = {}, o = s[s.length - 1], r = (new Date).getTime(); if (b && g && p > r - g) return a.clearTimeout(h), h = a.setTimeout(u, p), void 0; g = r; for (var v in l) { if (l.hasOwnProperty(v)) { var w = l[v], x = w.minw, y = w.maxw, z = null === x, A = null === y, B = "em"; x && (x = parseFloat(x) * (x.indexOf(B) > -1 ? i || t() : 1)), y && (y = parseFloat(y) * (y.indexOf(B) > -1 ? i || t() : 1)), w.hasquery && (z && A || !(z || e >= x) || !(A || y >= e)) || (f[w.media] || (f[w.media] = []), f[w.media].push(m[w.rules])) } } for (var C in n) { n.hasOwnProperty(C) && n[C] && n[C].parentNode === q && q.removeChild(n[C]) } n.length = 0; for (var D in f) { if (f.hasOwnProperty(D)) { var E = j.createElement("style"), F = f[D].join("\n"); E.type = "text/css", E.media = D, q.insertBefore(E, o.nextSibling), E.styleSheet ? E.styleSheet.cssText = F : E.appendChild(j.createTextNode(F)), n.push(E) } } }, v = function(a, b, d) { var e = a.replace(c.regex.keyframes, "").match(c.regex.media), f = e && e.length || 0; b = b.substring(0, b.lastIndexOf("/")); var g = function(a) { return a.replace(c.regex.urls, "$1" + b + "$2$3") }, h = !f && d; b.length && (b += "/"), h && ``` -------------------------------- ### Basic Dash App with Graph Component Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html A fundamental Dash application displaying a Plotly graph. Ensure Dash and Plotly are installed. ```python import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go app = dash.Dash(__name__) fig = go.Figure(data=go.Scatter(x=[1, 2], y=[2, 1])) app.layout = html.Div([ dcc.Graph(id='graph', figure=fig) ]) if __name__ == '__main__': app.run_server(debug=True) ``` -------------------------------- ### Run Integration Tests Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/README.md Execute the Selenium integration tests for Dash Core Components using the npm test command. ```bash npm test ``` -------------------------------- ### Creating a Dash App with Multiple Components Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Builds a Dash application with a graph and a slider, demonstrating basic interactivity. Requires Dash and Plotly. ```python import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objects as go app = dash.Dash(__name__) app.layout = html.Div([ html.H1('Dash App with Slider'), dcc.Graph(id='graph-with-slider'), dcc.Slider( id='slider-component', min=0, max=10, step=1, value=5, marks={i: str(i) for i in range(11)} ) ]) @app.callback( Output('graph-with-slider', 'figure'), [Input('slider-component', 'value')] ) def update_figure(selected_value): # Generate data based on slider value x_data = [i for i in range(selected_value + 1)] y_data = [i**2 for i in x_data] fig = go.Figure( data=[ go.Scatter(x=x_data, y=y_data, mode='lines+markers') ], layout=go.Layout( title=f'Graph for Value: {selected_value}' ) ) return fig if __name__ == '__main__': app.run_server(debug=True) ``` -------------------------------- ### Scatter Plot with Hover Information Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Creates a scatter plot where hovering over points displays custom text. Ensure Plotly is installed. ```python import plotly.graph_objects as go x_values = [1, 2, 3, 4] y_values = [10, 11, 12, 13] hover_texts = ['Point A', 'Point B', 'Point C', 'Point D'] fig = go.Figure(data=go.Scatter( x=x_values, y=y_values, mode='markers', marker=dict(size=12, color='blue'), text=hover_texts, # Text that appears on hover hoverinfo='text' )) fig.update_layout( title='Scatter Plot with Hover Info' ) fig.show() ``` -------------------------------- ### jQuery Animation Tick and Timer Management Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Manages the animation frame tick and timer queue. Starts and stops the animation interval. ```javascript m.fx.tick = function() { var a, b = m.timers, c = 0; for ($a = m.now(); c < b.length; c++) { a = b[c]; a() || b[c] !== a || b.splice(c--, 1); } b.length || m.fx.stop(); $a = void 0; }; m.fx.timer = function(a) { m.timers.push(a); a() ? m.fx.start() : m.timers.pop(); }; ``` -------------------------------- ### Bootstrap Affix Plugin Implementation Source: https://github.com/plotly/dash/blob/dev/components/dash-html-components/vignettes/dash-html-components.html Manages element positioning based on scroll events to create sticky-like behavior. ```javascript +function(a){ "use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); ``` -------------------------------- ### Dash Textarea Component Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html A basic example of a dccTextarea component. It includes placeholder text, an initial value, and styling to control its width. ```R library(dash) dccTextarea( placeholder = "Enter a value...", value = "This is a TextArea component", style = list("width" = "100%") ) ``` -------------------------------- ### Dash Checklist Component: Inline Labels Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html This example demonstrates a dccChecklist component where the labels are styled to display inline, allowing for a more compact layout. ```R library(dash) dccChecklist( options=list( list("label" = "New York City", "value" = "NYC"), list("label" = "Montréal", "value" = "MTL"), list("label" = "San Francisco", "value" = "SF") ), value=list("MTL", "SF"), labelStyle = list("display" = "inline-block") ) ``` -------------------------------- ### Configure DatePickerSingle RTL and First Day Source: https://github.com/plotly/dash/blob/dev/components/dash-core-components/vignettes/dash-core-components.html Sets the calendar to right-to-left orientation and defines Tuesday as the first day of the week. ```R dccDatePickerSingle( is_RTL=TRUE, first_day_of_week=3, date=format(as.Date("2017-6-21"), format = "%Y,%m,%d") ) # Displays "06/21/2017" ```