def create_examples(examples_data): examples = [] for example in examples_data: examples += [ html.H3(example['param_name'].title()), rc.Markdown(example['description']), rc.ComponentBlock(example['code']), html.Hr() ] return examples
layout = html.Div(children=[ html.H1('dcc.Checklist'), rc.Markdown(''' `dcc.Checklist` is a component for rendering a set of checkboxes. See also <dccLink href="/dash-core-components/radioitems" children="RadioItems"/> for selecting a single option at a time or <dccLink href="/dash-core-components/dropdown" children="Dropdown"/> for a more compact view. '''), rc.ComponentBlock('''import dash_core_components as dcc dcc.Checklist( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': 'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], value=['NYC', 'MTL'] )''', style=styles.code_container), rc.ComponentBlock('''import dash_core_components as dcc dcc.Checklist( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': 'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], value=['NYC', 'MTL'], labelStyle={'display': 'inline-block'}
def generate_component_example(component_name, library_name, library_short, description='', params=None, style=None, default_id=True, datafile=None, library_imports=None, setup_code='', component_wrap=None, image_info=None): '''Generate an example for a component, with hyperlinks to the appropriate component-specific pages. :param (str) component_name: The name of the component as it is defined within the package. :param (str) library_name: The full name of the library (e.g., dash_bio). :param (str) library_short: The short name of the library, used in an import statement (i.e., import library_name as library_short). :param (str) description: A short string describing the component. :param (dict) params: A dictionary that contains the parameters assigned to the component that is to be displayed as a live example; the keys correspond to the parameter names. :param (dict) style: A dictionary that contains any style options. The keys correspond to the style parameter names. :param (bool) default_id: Whether or not to assign a default ID to the component in the example code. :param (string) datafile: The name of the data file, if any, used for the component. This file should be present in the folder specified by the variable DATA_LOCATION_PREFIX. :param (list[list]) library_imports: A list for which each element is a list with two elements: the first element should be the full name of the library, and the second element should be the short name of the library. Contains all of the libraries necessary for running the example code (e.g., pandas). :param (str) setup_code: Any additional code required before rendering the component (e.g., parsing a data file). :param (str) component_wrap: A string that will wrap the component (e.g., if the component needs to be an argument for a dcc.Graph). The location of the component code is represented by an underscore (_). :param (dict) image_info: The URL and, if applicable, the height and width of the image of the component. :rtype (list[obj]): A list containing the entire section for the component in question, including the code block, component demo, description, and hyperlinks to the component-specific page. ''' # location of all sample data DATA_LOCATION_PREFIX = '''https://raw.githubusercontent.com/plotly/\ dash-bio-docs-files/master/''' if library_imports is None: library_imports = [] # parameters for initial declaration of component paramstring = '\n ' if default_id is True: paramstring += 'id=\'my-{}-{}\', '.format(library_short, component_name.lower()) if params is not None: for key in params.keys(): paramstring += '{}={}, '.format(key, params[key]) # style options if style is not None: styleString = 'style={\n ' for key in style.keys(): styleString += ' \'{}\': \'{}\', '.format(key, str(style[key])) # remove comma and space following the last style option styleString = styleString[:-2] styleString += '\n }, ' paramstring += styleString # loading data if necessary if datafile is not None: library_imports.append(['urllib.request', 'urlreq']) # only decode for python 3 decode_string = '' if sys.version_info >= (3, 0): decode_string = '.decode(\"utf-8\")' # add data location setup_code = '''\ndata = urlreq.urlopen(\n \"{}\" + \n \"{}\"\n).read(){}\n\n'''.format( DATA_LOCATION_PREFIX, datafile['name'], decode_string) + setup_code # declare data in component initialization if necessary if 'parameter' in datafile.keys(): paramstring += '{}=data, '.format(datafile['parameter']) # pretty-print param string (spaces for indentation) paramstring = paramstring.replace(', ', ',\n ') # remove the characters following the final parameter # (',\n '), and add unindented newline at end if (len(paramstring) > 4): paramstring = paramstring[:-4] + '\n' # if no params were supplied, remove all newlines else: paramstring = '' # format component string component_string = '{}.{}({})'.format(library_short, component_name, paramstring) # wrap component if necessary if component_wrap is not None: component_string = component_wrap.replace('_', component_string) # add imports imports_string = '' for library in library_imports: if library[0] != library[1]: imports_string += 'import {} as {}\n'.format( library[0], library[1]) else: imports_string += 'import {}\n'.format(library[0]) # change urllib package if necessary (due to Python version) imports_string = imports_string.replace('urllib.request', 'six.moves.urllib.request') # full code example_string = '''import {} as {} {} {} component = {} '''.format(library_name, library_short, imports_string, setup_code, component_string) # load the iframe if that is where the app is if image_info is not None: component_demo = imageComponentBlock(example_string, **image_info) else: component_demo = rc.ComponentBlock(example_string) # full component section return [ html.Hr(), html.H3( dcc.Link(component_name, href=tools.relpath('/{}/{}'.format( library_name.replace('_', '-'), component_name.lower())), id=component_name.replace(' ', '-').lower())), rc.Markdown(description), component_demo, html.Br(), dcc.Link('More {} Examples and Reference'.format(component_name), href=tools.relpath('/{}/{}'.format( library_name.replace('_', '-'), component_name.lower()))) ]
html.Td(rc.Markdown('`x`'), style={'text-align': 'left'}), html.Td(rc.Markdown('`1410715640579`'), style={'text-align': 'left'}), html.Td('Unix ms timestamp') ]), ]), html.Br(), html.H3("Display Format Examples"), rc.Markdown(""" You can utilize any permutation of the string tokens shown in the table above to change how selected dates are displayed in the `DatePickerSingle` component. """), rc.ComponentBlock('''import dash_core_components as dcc dcc.DatePickerSingle( date='2017-06-21', display_format='MMM Do, YY' )'''), rc.ComponentBlock('''import dash_core_components as dcc from datetime import date dcc.DatePickerSingle( date=date(2017,6,21), display_format='M-D-Y-Q', )'''), rc.ComponentBlock('''import dash_core_components as dcc from datetime import date dcc.DatePickerSingle( date=date(2017,6,21), display_format='MMMM Y, DD'
def generate_code_container(component_name, library_name, library_short, default_id=True, description='', props=None, style=None): ''' Generates a section for the component specified, including pretty-printed code containing top-level props (not dicts) and style dictionaries. :param (str) component_name: The component name in camelcase with the first letter also capitalized. :param (str) library_name: Name of the library the component belongs to, with words separated by dashes ('-'). :param (str) library_short: A short name for the library (e.g., "dcc"). :param (bool) default_id: Whether or not to generate an id for the component. Can be useful for custom styling. :param (dict) props: A dictionary of the component's keys and the values corresponding to those keys. :param (dict) style: A dictionary that determines the styling of the component, if 'style' is a property of that component. (Will fail if this is not true.) ''' propString = '\n ' if (default_id): propString += 'id=\'my-{}-{}\', '.format(library_short, component_name.lower()) if props is not None: for key in props.keys(): propString += '{}={}, '.format(key, props[key]) if style is not None: styleString = 'style={\n ' for key in style.keys(): styleString += ' \'{}\': \'{}\', '.format(key, str(style[key])) styleString = styleString[:-2] styleString += '\n }, ' propString += styleString propString = propString.replace(', ', ',\n ') if (len(propString) > 4): propString = propString[:-4] + '\n' else: propString = '' example_string = '''import {} as {} {}.{}({})'''.format(library_name.replace('-', '_'), library_short, library_short, component_name, propString) return [ html.Hr(), html.H3( dcc.Link(component_name, href=tools.relpath('/{}/{}'.format( library_name, component_name.lower())), id=component_name.replace(' ', '-').lower())), rc.Markdown(description), rc.ComponentBlock(example_string), html.Br(), dcc.Link('More {} Examples and Reference'.format(component_name), href=tools.relpath('/{}/{}'.format(library_name, component_name.lower()))) ]
rc.Markdown(''' ```py >>> import dash_core_components as dcc >>> print(dcc.__version__) {} ``` '''.format(dcc.__version__), style=styles.code_container), html.Hr(), html.H2(dcc.Link('Dropdown', href=tools.relpath('/dash-core-components/dropdown'))), rc.ComponentBlock('''import dash_core_components as dcc dcc.Dropdown( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': 'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], value='MTL' )''', style=styles.code_container), rc.ComponentBlock('''import dash_core_components as dcc dcc.Dropdown( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': 'Montréal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], multi=True, value="MTL"
any extra properties."), rc.Markdown(examples['dropdown.py'][0], style=styles.code_container), html.Div(examples['dropdown.py'][1], className='example-container', style={'overflow-x': 'initial'}), html.Hr(), html.H3('Multi-Value Dropdown'), rc.Markdown("A dropdown component with the `multi` property set to `True` \ will allow the user to select more than one value \ at a time."), rc.ComponentBlock('''import dash_core_components as dcc dcc.Dropdown( options=[ {'label': 'New York City', 'value': 'NYC'}, {'label': 'Montreal', 'value': 'MTL'}, {'label': 'San Francisco', 'value': 'SF'} ], value=['MTL', 'NYC'], multi=True )''', style=styles.code_container), html.Hr(), html.H3('Disable Search'), rc.Markdown("The `searchable` property is set to `True` by default on all \ `Dropdown` components. To prevent searching the dropdown \ value, just set the `searchable` property to `False`. \ Try searching for 'New York' on this dropdown below and compare \ it to the other dropdowns on the page to see the difference."), rc.ComponentBlock('''import dash_core_components as dcc dcc.Dropdown(
html.Hr(), html.H3('Default Boolean Switch'), html.P("An example of a default boolean switch without \ any extra properties."), rc.Markdown(examples['boolean-switch.py'][0], style=styles.code_container), html.Div(examples['boolean-switch.py'][1], className='example-container', style={'overflow-x': 'initial'}), html.Hr(), html.H3('Color'), rc.Markdown("Set the color of the boolean switch with \ `color=#<hex_value>`."), rc.ComponentBlock('''import dash_daq as daq daq.BooleanSwitch( on=True, color="#9B51E0", )''', style=styles.code_container), html.Hr(), html.H3('Label'), rc.Markdown( "Set the label and label position using the `label` and `labelPosition` \ properties."), rc.ComponentBlock('''import dash_daq as daq daq.BooleanSwitch( on=True, label="Label", labelPosition="top" )''',
in other environments like Jupyter, your console, and more. If you are using the interface outside of Dash, then calling `fig.show()` will always display the graph (either in your browser or inline directly in your environment). To see all of these rendering environments, see https://plot.ly/python/renderers/. """), html.H2('Examples'), html.H3('Plotly Express in Dash'), dcc.Markdown( 'The `fig` object is passed directly into the `figure` property of `dcc.Graph`:' ), rc.ComponentBlock(''' import dash_core_components as dcc import plotly.express as px df = px.data.iris() # iris is a pandas DataFrame fig = px.scatter(df, x="sepal_width", y="sepal_length") dcc.Graph(figure=fig) '''), dcc.Markdown(""" ### Using the Low-Level Interface with `go.Figure` Read through (1) above to learn more about the difference between `px` & `go.Figure`. """), rc.ComponentBlock('''import dash_core_components as dcc import plotly.graph_objs as go fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])]) dcc.Graph( id='example-graph-2', figure=fig
from dash_docs import styles from dash_docs import tools from dash_docs import reusable_components as rc examples = tools.load_examples(__file__) layout = html.Div(children=[ html.H1("Markdown Examples and Reference"), html.H2("Headers"), rc.ComponentBlock("""import dash_core_components as dcc dcc.Markdown(''' # This is an <h1> tag ## This is an <h2> tag ###### This is an <h6> tag ''')"""), html.H2("Emphasis"), rc.ComponentBlock("""import dash_core_components as dcc dcc.Markdown(''' *This text will be italic* _This will also be italic_ **This text will be bold**
html.Div(examples['slider.py'][1], className='example-container'), html.H3('Marks and Steps'), rc.Markdown("If slider `marks` are defined and `step` is set to `None` \ then the slider will only be able to select values that \ have been predefined by the `marks`. Note that the default \ is `step=1`, so you must explicitly specify `None` to get \ this behavior.`marks` is a `dict` where the keys represent \ the numerical values and the values represent their labels."), rc.ComponentBlock('''import dash_core_components as dcc dcc.Slider( min=0, max=10, step=None, marks={ 0: '0 °F', 3: '3 °F', 5: '5 °F', 7.65: '7.65 °F', 10: '10 °F' }, value=5 )''', style=styles.code_container), html.H3('Included and Styling Marks'), rc.Markdown("By default, `included=True`, meaning the rail trailing the \ handle will be highlighted. To have the handle act as a \ discrete value set `included=False`. To style `marks`, \ include a style css attribute alongside the key value."), rc.ComponentBlock('''import dash_core_components as dcc # Slider has included=True by default
html.Tr([ html.Td(rc.Markdown('`x`'), style={'text-align': 'left'}), html.Td(rc.Markdown('`1410715640579`'), style={'text-align': 'left'}), html.Td('Unix ms timestamp') ]), ]), html.Br(), html.H3("Display Format Examples"), rc.Markdown("You can utilize any permutation of the string tokens \ shown in the table above to change how selected dates are \ displayed in the `DatePickerRange` component."), rc.ComponentBlock('''import dash_core_components as dcc from datetime import datetime as dt dcc.DatePickerRange( end_date=dt(2017,6,21,23,59,59,999999), display_format='MMM Do, YY', start_date_placeholder_text='MMM Do, YY' )'''), rc.ComponentBlock('''import dash_core_components as dcc from datetime import datetime as dt dcc.DatePickerRange( end_date=dt(2017,6,21), display_format='M-D-Y-Q', start_date_placeholder_text='M-D-Y-Q' )'''), rc.ComponentBlock('''import dash_core_components as dcc from datetime import datetime as dt dcc.DatePickerRange( end_date=dt(2017,6,21),
className='example-container', style={'overflow': 'hidden'}), html.H3('Marks and Steps'), rc.Markdown("If slider `marks` are defined and `step` is set to `None` \ then the slider will only be able to select values that \ have been predefined by the `marks`. \ Note that the default is `step=1`, so you must explicitly \ specify `None` to get this behavior."), rc.ComponentBlock('''import dash_core_components as dcc dcc.RangeSlider( min=0, max=10, step=None, marks={ 0: '0 °F', 3: '3 °F', 5: '5 °F', 7.65: '7.65 °F', 10: '10 °F' }, value=[3, 7.65] )''', style=styles.code_container), html.H3('Included and Styling Marks'), rc.Markdown("By default, `included=True`, meaning the rail trailing the \ handle will be highlighted. To have the handle act as a \ discrete value set `included=False`. To style `marks`, \ include a style css attribute alongside the key value."), rc.ComponentBlock('''import dash_core_components as dcc # RangeSlider has included=True by default