├── .gitignore
├── DashTemplateFramework
├── DropdownList
│ ├── dashboard_diff_label_value.py
│ ├── dashboard_disablesearch_dropdown.py
│ ├── dashboard_multiSelections.py
│ ├── dashboard_multidropdowns.py
│ ├── dashboard_placeholder_dropdownlist.py
│ ├── dashboard_singleSelection.py
│ ├── dropdown_diff_label_value.png
│ ├── dropdown_placeholder.png
│ ├── dropdwon_disablesearch.png
│ ├── multipleSelections_dropdowns.png
│ ├── multiple_dropdowns.png
│ ├── readme.md
│ └── single_dropdown.png
├── Multitabs
│ ├── dashboard_onediv.py
│ ├── dashboard_structure.py
│ ├── one_div.png
│ └── readme.md
└── readme.md
├── DashboardExample
├── DashExample.py
├── Data
│ ├── Console_share_CA.csv
│ ├── Console_share_GB.csv
│ ├── Console_share_HK.csv
│ ├── Console_share_JP.csv
│ ├── Console_share_KR.csv
│ ├── Console_share_US.csv
│ ├── Console_share_WorldWide.csv
│ ├── Markdown_CA.txt
│ ├── Markdown_GB.txt
│ ├── Markdown_HK.txt
│ ├── Markdown_JP.txt
│ ├── Markdown_KR.txt
│ ├── Markdown_US.txt
│ ├── Markdown_WorldWide.txt
│ └── source.txt
├── Images
│ ├── Dash@2x.jpg
│ ├── gaming_dashboard.png
│ ├── gaming_dashboard_bar.png
│ └── gaming_dashboard_layout.png
└── Readme.md
├── DockerizeDash
├── Dockerfile
├── display_dash.py
├── readme.md
└── requirements.txt
├── Part1
├── README.md
├── computer_security_dash.png
├── dash_part1.py
├── data.csv
├── example1_whisky.py
├── example2_existing_plotly.py
├── whisky_dash.png
└── whisky_plotly.png
├── Part2
├── Air_Traffic_Passenger_Statistics.csv
├── dash_inputs.py
├── dash_slider.py
├── dash_slider_pic.png
├── example3_cap.png
├── example3_slider.py
├── example4_cap.png
├── example4_filter1.png
├── example4_multinput.py
├── example5_cap.png
├── example5_multioutputs.py
├── example5_output.png
├── example6_markdown.py
├── example_filter2.png
└── readme.md
├── Part3
├── example7_hover.png
├── example7_interactive.py
├── example7_selections.png
└── readme.md
├── PlotlyExample
├── BarChart
│ ├── Groupbar.py
│ ├── HorizontalBar.py
│ ├── Readme.md
│ ├── Simplebar.py
│ ├── Stackbar.py
│ ├── bar.png
│ ├── groupbar.png
│ ├── hbar.png
│ └── stackbar.png
├── BoxPlot
│ ├── Readme.md
│ ├── box.png
│ └── boxplot_simple.py
├── CandlestickChart
│ ├── AAPLprice.py
│ ├── Candlestick.png
│ └── Readme.md
├── ChoroplethGraph
│ ├── Example_Basic_ChoroplethGraph.py
│ ├── Readme.md
│ └── basic_choropleth.png
├── Data
│ ├── county_avg_rent.csv
│ ├── countyfips.csv
│ ├── cust_num.csv
│ ├── ecom_funnel.csv
│ ├── expense_dept.csv
│ ├── expense_everybody.csv
│ ├── grades.csv
│ ├── hk_population.csv
│ ├── revenue_dept.csv
│ ├── salary.csv
│ └── tips.csv
├── FunnelChart
│ ├── readme.md
│ ├── simple_funnel.png
│ ├── simple_funnel.py
│ ├── simple_funnelarea.py
│ ├── simple_funnelarea1.png
│ ├── simple_funnelarea2.png
│ ├── stack_funnel.png
│ └── stack_funnel.py
├── Heatmap
│ ├── Readme.md
│ ├── Simple_heatmap.py
│ └── simpleheatmap.png
├── Histogram
│ ├── AggregatedHistogram.py
│ ├── CumulativeHistogram.py
│ ├── NormalizedHistogram.py
│ ├── OverlaidHistogram.py
│ ├── Readme.md
│ ├── SimpleHistogram.py
│ ├── StackedHistogram.py
│ ├── aggregated_histogram.png
│ ├── cumulative_histogram.png
│ ├── normalized_histogram.png
│ ├── overlaid_histogram.png
│ ├── simple_histogram.png
│ └── stacked_histogram.png
├── LineChart
│ ├── Mutlilines_Linechart.py
│ ├── SimpleLinechart.py
│ ├── SimpleLinechart_points.py
│ ├── multilines.png
│ ├── readme.md
│ ├── simple_linechart.png
│ └── simple_linechart_points.png
├── ParallelCoordinatesPlot
│ ├── complex_parcoords.png
│ ├── complex_pcate.py
│ ├── readme.md
│ ├── simple_parcoords.png
│ ├── simple_parcoords_constrain.png
│ └── simple_pcate.py
├── PieChart
│ ├── Multiple_pies.py
│ ├── Pretty_pie.py
│ ├── Readme.md
│ ├── Simple_donut.py
│ ├── Simple_pie.py
│ ├── multi_pies.png
│ ├── prettypie.png
│ ├── simpledonut.png
│ └── simplepie.png
├── Readme.md
├── SankeyChart
│ ├── plotly_example.png
│ ├── plotlyexample_sankey.py
│ ├── readme.md
│ ├── simple_sankey.png
│ └── simple_sankey.py
├── ScatterPlot
│ ├── Bubblechart.py
│ ├── Bubblechart_legend.py
│ ├── CateColourScatterplot.py
│ ├── CateColourScatterplot_legend.py
│ ├── NumColourScatterplot.py
│ ├── SimpleScatterplot.py
│ ├── bubblechart.png
│ ├── bubblechart_legend.png
│ ├── catedim_scatterplot.png
│ ├── catedim_scatterplot_legend.png
│ ├── numdim_scatterplot.png
│ ├── readme.md
│ └── simple_scatterplot.png
├── SunburstChart
│ ├── readme.md
│ ├── simple_sunburst.png
│ ├── simple_sunburst_agsunset.png
│ ├── simplesunburst.py
│ └── simplesunburst_colourscale.py
└── Treemap
│ ├── PlotlyExample_treemap.py
│ ├── SalaryExample_treemap.py
│ ├── plotly_treemap.png
│ ├── readme.md
│ └── salary_treemap.png
├── PlotlyTemplateFramework
├── .gitignore
├── TemplateExamples
│ ├── aggregatedhistogram_arguements.json
│ ├── boxplot_arguements.json
│ ├── bubblechart_arguements.json
│ ├── candlestick_arguements.json
│ ├── catecolour_scatter_arguement.json
│ ├── catehistogram_arguements.json
│ ├── complexbar_arguements.json
│ ├── horizontalbar_arguements.json
│ ├── multilines_arguements.json
│ ├── normalizedhistogram_arguements.json
│ ├── numcolour_scatter_arguements.json
│ ├── readme.md
│ ├── simplebar_arguements.json
│ ├── simplefunnel_arguements.json
│ ├── simplefunnelarea_arguements.json
│ ├── simpleheatmap_arguements.json
│ ├── simplehistogram_arguements.json
│ ├── simpleline_arguements.json
│ ├── simplepie_arguements.json
│ ├── simplescatter_arguements.json
│ └── stackfunnel_arguements.json
├── arguements.json
├── call_plotly.py
├── check_metadata.py
├── css_colours.py
├── data.py
├── generate_bar.py
├── generate_boxplot.py
├── generate_candlestick.py
├── generate_funnel.py
├── generate_heatmap.py
├── generate_histogram.py
├── generate_line.py
├── generate_pie.py
├── generate_plotly.py
├── generate_scatterplot.py
├── layout.py
└── readme.md
└── readme.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # iOS related
2 | .DS_Store
3 |
4 | # Repository-specific
5 | *.html
6 |
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 | *$py.class
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | share/python-wheels/
30 | *.egg-info/
31 | .installed.cfg
32 | *.egg
33 | MANIFEST
34 |
35 | # PyInstaller
36 | # Usually these files are written by a python script from a template
37 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
38 | *.manifest
39 | *.spec
40 |
41 | # Installer logs
42 | pip-log.txt
43 | pip-delete-this-directory.txt
44 |
45 | # Unit test / coverage reports
46 | htmlcov/
47 | .tox/
48 | .nox/
49 | .coverage
50 | .coverage.*
51 | .cache
52 | nosetests.xml
53 | coverage.xml
54 | *.cover
55 | *.py,cover
56 | .hypothesis/
57 | .pytest_cache/
58 | cover/
59 |
60 | # Translations
61 | *.mo
62 | *.pot
63 |
64 | # Django stuff:
65 | *.log
66 | local_settings.py
67 | db.sqlite3
68 | db.sqlite3-journal
69 |
70 | # Flask stuff:
71 | instance/
72 | .webassets-cache
73 |
74 | # Scrapy stuff:
75 | .scrapy
76 |
77 | # Sphinx documentation
78 | docs/_build/
79 |
80 | # PyBuilder
81 | .pybuilder/
82 | target/
83 |
84 | # Jupyter Notebook
85 | .ipynb_checkpoints
86 |
87 | # IPython
88 | profile_default/
89 | ipython_config.py
90 |
91 | # pyenv
92 | # For a library or package, you might want to ignore these files since the code is
93 | # intended to run in multiple environments; otherwise, check them in:
94 | # .python-version
95 |
96 | # pipenv
97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
100 | # install all needed dependencies.
101 | #Pipfile.lock
102 |
103 | # poetry
104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105 | # This is especially recommended for binary packages to ensure reproducibility, and is more
106 | # commonly ignored for libraries.
107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108 | #poetry.lock
109 |
110 | # pdm
111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112 | #pdm.lock
113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114 | # in version control.
115 | # https://pdm.fming.dev/#use-with-ide
116 | .pdm.toml
117 |
118 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
119 | __pypackages__/
120 |
121 | # Celery stuff
122 | celerybeat-schedule
123 | celerybeat.pid
124 |
125 | # SageMath parsed files
126 | *.sage.py
127 |
128 | # Environments
129 | .env
130 | .venv
131 | env/
132 | venv/
133 | ENV/
134 | env.bak/
135 | venv.bak/
136 |
137 | # Spyder project settings
138 | .spyderproject
139 | .spyproject
140 |
141 | # Rope project settings
142 | .ropeproject
143 |
144 | # mkdocs documentation
145 | /site
146 |
147 | # mypy
148 | .mypy_cache/
149 | .dmypy.json
150 | dmypy.json
151 |
152 | # Pyre type checker
153 | .pyre/
154 |
155 | # pytype static type analyzer
156 | .pytype/
157 |
158 | # Cython debug symbols
159 | cython_debug/
160 |
161 | # PyCharm
162 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
163 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
164 | # and can be added to the global gitignore or merged into this file. For a more nuclear
165 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
166 | #.idea/
167 |
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dashboard_diff_label_value.py:
--------------------------------------------------------------------------------
1 | import dash
2 | from dash import dcc, html
3 | from dash.dependencies import Input, Output, State
4 | """
5 | Import other necessary packages
6 | """
7 |
8 | """
9 | Load your data here
10 | """
11 |
12 | """
13 | Define Figure here
14 | """
15 | # Replace dropdown list here
16 | dropdown_choices = [{'label':'Choice 1', 'value':'I am picking Choice 1'},
17 | {'label':'Choice 2', 'value':'I am picking Choice 2'},
18 | {'label':'Choice 3', 'value':'I am picking Choice 3'}]
19 | dropdown_alignment = 'left' # left, center, right
20 |
21 | # Dash Set up
22 | num_tab = 2
23 | port = 8000
24 | app = dash.Dash()
25 | app.layout = html.Div([
26 | html.P('Select:'),
27 | dcc.Dropdown(id='dropdown-choices',
28 | options=dropdown_choices,
29 | value=dropdown_choices[0]['value'],
30 | style={'width':'70%','text-align':dropdown_alignment}
31 | ),
32 | html.P(id='display')
33 | ])
34 |
35 |
36 |
37 | # Display Dropdown Selection
38 | @app.callback([Output('display','children')],
39 | [Input('dropdown-choices','value')])
40 | def display_choice(choice):
41 | return [choice]
42 |
43 | # Initiate dashboard
44 | if __name__ == '__main__':
45 | app.run_server(debug=True, port=port)
46 |
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dashboard_disablesearch_dropdown.py:
--------------------------------------------------------------------------------
1 | import dash
2 | from dash import dcc, html
3 | from dash.dependencies import Input, Output, State
4 | """
5 | Import other necessary packages
6 | """
7 |
8 | """
9 | Load your data here
10 | """
11 |
12 | """
13 | Define Figure here
14 | """
15 | # Replace dropdown list here
16 | dropdown_choices = ['Choice 1', 'Choice 2', 'Choice 3']
17 | dropdown_alignment = 'left' # left, center, right
18 |
19 | # Dash Set up
20 | num_tab = 2
21 | port = 8000
22 | app = dash.Dash()
23 | app.layout = html.Div([
24 | html.P('Select:'),
25 | dcc.Dropdown(id='dropdown-choices',
26 | options=dropdown_choices,
27 | value=dropdown_choices[0],
28 | searchable=False,
29 | style={'width':'70%','text-align':dropdown_alignment}
30 | ),
31 | html.P(id='display')
32 | ])
33 |
34 |
35 |
36 | # Display Dropdown Selection
37 | @app.callback([Output('display','children')],
38 | [Input('dropdown-choices','value')])
39 | def display_choice(choice):
40 | return [choice]
41 |
42 | # Initiate dashboard
43 | if __name__ == '__main__':
44 | app.run_server(debug=True, port=port)
45 |
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dashboard_multiSelections.py:
--------------------------------------------------------------------------------
1 | import dash
2 | from dash import dcc, html
3 | from dash.dependencies import Input, Output, State
4 | """
5 | Import other necessary packages
6 | """
7 |
8 | """
9 | Load your data here
10 | """
11 |
12 | """
13 | Define Figure here
14 | """
15 | # Replace dropdown list here
16 | dropdown_choices = ['Choice 1', 'Choice 2', 'Choice 3',
17 | 'Choice 4', 'Choice 5']
18 | dropdown_alignment = 'left' # left, center, right
19 |
20 | # Dash Set up
21 | num_tab = 2
22 | port = 8000
23 | app = dash.Dash()
24 | app.layout = html.Div([
25 | html.P('Select:'),
26 | dcc.Dropdown(id='dropdown-choices',
27 | options=dropdown_choices,
28 | value=[dropdown_choices[0]],
29 | multi=True, # Allow multiple selections
30 | style={'width':'70%','text-align':dropdown_alignment}
31 | ),
32 | html.P(id='display')
33 | ])
34 |
35 |
36 |
37 | # Display Dropdown Selection
38 | @app.callback([Output('display','children')],
39 | [Input('dropdown-choices','value')])
40 | def display_choice(choice):
41 | return [', '.join(choice)]
42 |
43 | # Initiate dashboard
44 | if __name__ == '__main__':
45 | app.run_server(debug=True, port=port)
46 |
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dashboard_multidropdowns.py:
--------------------------------------------------------------------------------
1 | import dash
2 | from dash import dcc, html
3 | from dash.dependencies import Input, Output, State
4 | """
5 | Import other necessary packages
6 | """
7 |
8 | """
9 | Load your data here
10 | """
11 |
12 | """
13 | Define Figure here
14 | """
15 | # Replace dropdown list here
16 | dropdown_choices1 = ['Choice 1', 'Choice 2', 'Choice 3']
17 | dropdown_choicesA = ['Choice A', 'Choice B', 'Choice C']
18 | dropdown_alignment = 'left' # left, center, right
19 |
20 | # Dash Set up
21 | num_tab = 2
22 | port = 8000
23 | app = dash.Dash()
24 | app.layout = html.Div([
25 | html.Div([
26 | html.P('Select:'),
27 | dcc.Dropdown(id='dropdown-choices1',
28 | options=dropdown_choices1,
29 | value=dropdown_choices1[0],
30 | style={'width':'70%','text-align':dropdown_alignment}
31 | ),
32 |
33 | ], style={'width':'80%', 'display':'inline-block'}),
34 | html.Div([
35 | html.P('Select:'),
36 | dcc.Dropdown(id='dropdown-choicesA',
37 | options=dropdown_choicesA,
38 | value=dropdown_choicesA[0],
39 | style={'width':'70%','text-align':dropdown_alignment}
40 | ),
41 |
42 | ], style={'width':'18%', 'display':'inline-block'}),
43 | html.P(id='display1'),
44 | html.P(id='displayA')
45 | ])
46 |
47 |
48 |
49 | # Display Numerical Choice
50 | @app.callback([Output('display1','children')],
51 | [Input('dropdown-choices1','value')])
52 | def display_choice(choice):
53 | return [choice]
54 |
55 | # Display Alphabetical Choice
56 | @app.callback([Output('displayA','children')],
57 | [Input('dropdown-choicesA','value')])
58 | def display_choice(choice):
59 | return [choice]
60 |
61 | # Initiate dashboard
62 | if __name__ == '__main__':
63 | app.run_server(debug=True, port=port)
64 |
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dashboard_placeholder_dropdownlist.py:
--------------------------------------------------------------------------------
1 | import dash
2 | from dash import dcc, html
3 | from dash.dependencies import Input, Output, State
4 | """
5 | Import other necessary packages
6 | """
7 |
8 | """
9 | Load your data here
10 | """
11 |
12 | """
13 | Define Figure here
14 | """
15 | # Replace dropdown list here
16 | dropdown_choices = ['Choice 1', 'Choice 2', 'Choice 3']
17 | dropdown_alignment = 'left' # left, center, right
18 |
19 | # Dash Set up
20 | num_tab = 2
21 | port = 8000
22 | app = dash.Dash()
23 | app.layout = html.Div([
24 | dcc.Dropdown(id='dropdown-choices',
25 | options=dropdown_choices,
26 | placeholder="Select a choice:",
27 | clearable=False, # Optional to add a clearable selection
28 | style={'width':'70%','text-align':dropdown_alignment}
29 | ),
30 | html.P(id='display')
31 | ])
32 |
33 |
34 |
35 | # Display Dropdown Selection
36 | @app.callback([Output('display','children')],
37 | [Input('dropdown-choices','value')])
38 | def display_choice(choice):
39 | return [choice]
40 |
41 | # Initiate dashboard
42 | if __name__ == '__main__':
43 | app.run_server(debug=True, port=port)
44 |
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dashboard_singleSelection.py:
--------------------------------------------------------------------------------
1 | import dash
2 | from dash import dcc, html
3 | from dash.dependencies import Input, Output, State
4 | """
5 | Import other necessary packages
6 | """
7 |
8 | """
9 | Load your data here
10 | """
11 |
12 | """
13 | Define Figure here
14 | """
15 | # Replace dropdown list here
16 | dropdown_choices = ['Choice 1', 'Choice 2', 'Choice 3']
17 | dropdown_alignment = 'left' # left, center, right
18 |
19 | # Dash Set up
20 | num_tab = 2
21 | port = 8000
22 | app = dash.Dash()
23 | app.layout = html.Div([
24 | html.P('Select:'),
25 | dcc.Dropdown(id='dropdown-choices',
26 | options=dropdown_choices,
27 | value=dropdown_choices[0],
28 | style={'width':'70%','text-align':dropdown_alignment}
29 | ),
30 | html.P(id='display')
31 | ])
32 |
33 |
34 |
35 | # Display Dropdown Selection
36 | @app.callback([Output('display','children')],
37 | [Input('dropdown-choices','value')])
38 | def display_choice(choice):
39 | return [choice]
40 |
41 | # Initiate dashboard
42 | if __name__ == '__main__':
43 | app.run_server(debug=True, port=port)
44 |
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dropdown_diff_label_value.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashTemplateFramework/DropdownList/dropdown_diff_label_value.png
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dropdown_placeholder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashTemplateFramework/DropdownList/dropdown_placeholder.png
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/dropdwon_disablesearch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashTemplateFramework/DropdownList/dropdwon_disablesearch.png
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/multipleSelections_dropdowns.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashTemplateFramework/DropdownList/multipleSelections_dropdowns.png
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/multiple_dropdowns.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashTemplateFramework/DropdownList/multiple_dropdowns.png
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/readme.md:
--------------------------------------------------------------------------------
1 | # Dropdown List
2 | Dropdown list allows users to select predefined selctions, both single and mutliple selections.
3 |
4 | ## Modules
5 | ### dashboard_singleSelection.py
6 | This module allows user to select a choice from a dropdown list, along with a call function.
7 |
8 |
9 |
10 | ### dashboard_multipleSelections.py
11 | This module allows user to select one or more choices from a dropdown list, along with a call function.
12 |
13 |
14 |
15 | ### dashboard_multidropdowns.py
16 | This module places two dropdown lists side-by-side, and display both selections in the text box below the dropdown list.
17 |
18 |
19 |
20 |
21 | Note: Adding display:inline-block in the Divs' style parameter to set two Divs to place side-by-side.
22 |
23 | ### dashboard_diff_label_value.py
24 | This module allows user to select a choice from a dropdown list, along with a call function. The function will capture the value assoication with the selection, instead of the selection label itself.
25 |
26 |
27 |
28 | ### dashboard_placeholder_dropdownlist.py
29 | This module allows developers to place the instruction as placeholder in the dropdown list and disable users to clear the selection.
30 |
31 |
32 |
33 | ### dashboard_disablesearch_dropdown.py
34 | This moduel prevents users to type and search for their selection, but to select only from the dropdown list.
35 |
36 |
37 |
38 | ## How the example works?
39 | ### Example 1 - Single Selection
40 | Select a choice from the dropdown list, and it will display it in the text box below the dropdown list.
41 |
42 | ### Example 2 - Multiple Selections
43 | Select the choice(s) from the dropdown list, and it will display all the selection in one string in the text box below the dropdown list.
44 |
45 | ### Example 3 - Multiple Dropdown List in one Row
46 | Select a choice from either dropdown list, and the choices will be display in the text box below dropdown list. The dropdown lists work independently, therefore, the callback functions only rely one dropdown list selection at a time.
47 |
48 | ### Example 4 - Dropdown of Selections with Value different with Label displayed
49 | This is an example on displaying readable label on the dropdown, and return programable text (value) in the backend. When select a choice from the dropdown list, it will display the text association with such selection for backend to consume. In this example, it will simply display that value.
50 |
51 | ### Example 5 - Cleaner Design and Select only from the Dropdown List
52 | This example allows developer omit the textbox above the dropdown list for instruction, and place it in the dropdown list instead. The example also disable to clear the selection in the dropdown
53 |
54 | ### Example 6 - Disable Search in the Dropdown List
55 | Users are expected to pick the selection without any typing.
56 |
57 | ## Reference
58 | Plotly Documentation on Dropdown List link
--------------------------------------------------------------------------------
/DashTemplateFramework/DropdownList/single_dropdown.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashTemplateFramework/DropdownList/single_dropdown.png
--------------------------------------------------------------------------------
/DashTemplateFramework/Multitabs/dashboard_onediv.py:
--------------------------------------------------------------------------------
1 | import dash
2 | from dash import dcc, html
3 | from dash.dependencies import Input, Output, State
4 | from dashboard_structure import layout
5 | """
6 | Import other necessary packages
7 | """
8 |
9 | """
10 | Load your data here
11 | """
12 |
13 | """
14 | Define Figure here
15 | """
16 | def figure1():
17 | return {'data': [{
18 | 'x': [1, 2, 3],
19 | 'y': [3, 1, 2],
20 | 'type': 'bar'
21 | }]}
22 |
23 | def figure2():
24 | return {'data': [{
25 | 'x': [1, 2, 3],
26 | 'y': [5, 10, 6],
27 | 'type': 'bar'
28 | }]}
29 |
30 | # Dash Set up
31 | num_tab = 2
32 | port = 8000
33 | app = dash.Dash()
34 | app = layout(app, num_tab)
35 |
36 | # Display Income Statement
37 | @app.callback([Output('content','children')],
38 | [Input('dashboard-tabs','value')])
39 | def display_income_statement(tab):
40 | if tab == 'label_1':
41 | return [html.Div(dcc.Graph(figure=figure1()))]
42 | return [html.Div(dcc.Graph(figure=figure2()))]
43 |
44 | # Initiate dashboard
45 | if __name__ == '__main__':
46 | app.run_server(debug=True, port=port)
47 |
--------------------------------------------------------------------------------
/DashTemplateFramework/Multitabs/dashboard_structure.py:
--------------------------------------------------------------------------------
1 | from dash import dcc, html
2 |
3 |
4 | def create_tabs(labels):
5 | tabs = []
6 | for i in labels:
7 | tabs.append(
8 | dcc.Tab(
9 | label=i, value=i
10 | )
11 | )
12 | return tabs
13 |
14 |
15 | def layout(app, num_tab):
16 | labels = [f'label_{i+1}' for i in range(num_tab)]
17 | app.layout = html.Div([
18 | dcc.Tabs(
19 | id='dashboard-tabs',value=labels[0],
20 | children=create_tabs(labels)
21 | ),
22 | html.Div(id='content')
23 | ])
24 | return app
25 |
--------------------------------------------------------------------------------
/DashTemplateFramework/Multitabs/one_div.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashTemplateFramework/Multitabs/one_div.png
--------------------------------------------------------------------------------
/DashTemplateFramework/Multitabs/readme.md:
--------------------------------------------------------------------------------
1 | # Multitabs
2 | Multi-tabs module allows users to display the dashboard on the selected category in the dashboard. There are two approaches and this folder includes the modules with both approaches.
3 |
4 | ## Module
5 | There are 2 approaches to create multitabs:
6 |
7 | - Create a Div independent of individual tabs (One Div-approach)
8 | - Create a Div along with all individual tabs (MultiDiv-approach) - Not recommended
9 |
10 |
11 | With the first approach, it allows the code to be more dynamic, flexible and robust without declare each a Div in each tab. With the second approach, it allows you to have Div's more customized layout under each tab and without loading every time switching back and forth between tabs.
12 |
13 | The second approach only works for Plotly chart is static because the callback function only works on one Div/Graph component. If there are two tabs with two Graph component, the callback function can only handles one component at a time. But the input will mess up another function and create errors, and thus only works for static to prevent another component to re-render with incorrect parameters. Therefore, this approach is not recommended for dynamic dashboard.
14 |
15 | ### One Div-Approach
16 | The module allows user to select the tab. The visualization is independent from the tab so it will trigger and re-generate the visualization when a tab is selected.
17 |
18 |
19 |
20 |
21 | ## Reference
22 | link: here
--------------------------------------------------------------------------------
/DashTemplateFramework/readme.md:
--------------------------------------------------------------------------------
1 | # Dash Template Framework
2 | The goal of this subsection is to provide some prebuilt Dash structures to build your dashboard quickly and convienently. The scripts are written in Python.
3 |
4 | ## Multi-tabs Dashboard
5 | Multi-tabs module allows users to display the dashboard on the selected category in the dashboard. You may find the module with multiple tabs in the [Multi-tabs](Multitabs) folder.
6 |
7 | ## Dropdown List
8 | Dropdown list allows users to select predefined selctions, both single and mutliple selections. You may find the module with a dropdown list in the [Dropdown List](DropdownList) folder.
--------------------------------------------------------------------------------
/DashboardExample/DashExample.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly.graph_objs as go
3 | import dash
4 | import dash_core_components as dcc
5 | import dash_html_components as html
6 | from dash.dependencies import Input, Output
7 |
8 |
9 | # Define the regions and the full name
10 | regions = {'CA': 'Canada', 'GB': 'Great Britain', 'HK': 'Hong Kong',
11 | 'JP': 'Japan', 'KR': 'South Korea', 'US': 'United States',
12 | 'WorldWide': 'World Wide'}
13 | region2brief = dict([(regions[k], k) for k in regions])
14 |
15 | # Read multiple data set
16 | filepath = 'Data/Console_share_'
17 | df = []
18 | for region in regions:
19 | filepath_curr = filepath + region + '.csv'
20 | df_temp = pd.read_csv(filepath_curr)
21 | rows = df_temp.shape[0]
22 | df_temp['Region'] = [regions[region] for _ in range(rows)]
23 | df.append(df_temp)
24 |
25 | df = pd.concat(df)
26 | df = df.drop('Other', axis=1)
27 | df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m')
28 |
29 |
30 | # Dash Set up
31 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
32 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
33 |
34 | # Dropdown list and radio button options set up
35 | region_dropdown = [{'label': regions[region], 'value': regions[region]} \
36 | for region in regions]
37 | vis_type_options = [{'label': 'Line Chart', 'value': 'line'},
38 | {'label': 'Bar Chart', 'value': 'bar'}]
39 |
40 | # Declare headline and description
41 | headline = 'Gaming Console Marketshare in 2018'
42 | description = '''
43 | The marketshare of gaming console is different in
44 | every corner in the world. For exmample, the marketshare
45 | of Xbox in Japan is significantly lower than the marketshare
46 | in the US. In this dashboard, you may select the region in
47 | the dropdown list below and the visualization. A brief
48 | analysis of the gaming market share in the
49 | selected region will be displayed under the graph.
50 | '''
51 |
52 | # Dashboard layout
53 | app.layout = html.Div([
54 | html.H1(children=headline, style={'text-align':'center'}),
55 | # Position 0, headline
56 | html.Div(children=description, style={'width':'60%'}),
57 | # Position 1, descritpion
58 | html.Div([
59 | html.Div([
60 | html.P('Select Region:'),
61 | dcc.Dropdown(
62 | id='region-dropdown',
63 | options=region_dropdown,
64 | value='World Wide',
65 | style={'width': '90%'}
66 | )
67 | ], style={'width':'60%', 'display': 'inline-block',
68 | 'vertical-align': 'middle'}),
69 | html.Div([
70 | html.P('Select Visualization:'),
71 | dcc.RadioItems(
72 | id='type-radio',
73 | options=vis_type_options,
74 | value='line'
75 | )
76 | ], style={'width':'40%', 'display': 'inline-block',
77 | 'vertical-align': 'middle'})
78 | ]), # Position 2, Options
79 | html.Div(dcc.Graph(id='vis')), # Position 3, Graph
80 | html.Div(dcc.Markdown(id='markdown'), style={'width':'60%'})
81 | # Position 4, Markdown
82 | ]) # End Dashboard Div
83 |
84 | def getLineChart(df, title):
85 | traces = []
86 | for console in df.columns:
87 | if console != 'Date' and console != 'Region':
88 | traces.append(dict(
89 | x=df['Date'],
90 | y=df[console],
91 | mode='lines+markers',
92 | marker={
93 | 'size': 15,
94 | 'line': {'width': 0.5, 'color': 'white'}
95 | },
96 | name=console
97 | ))
98 | layout = dict(title=title,
99 | xaxis={'title':'Date'},
100 | yaxis={'title':'Market Share (%)', 'range': [0,100]},
101 | transition={'duration': 500})
102 | return {'data': traces, 'layout': layout}
103 |
104 | def getBarChart(df, title):
105 | df = df.drop(['Region'], axis=1)
106 | data = []
107 | for console in df.columns:
108 | if console != 'Date':
109 | temp = {}
110 | temp['x'] = df['Date']
111 | temp['y'] = df[console]
112 | temp['type'] = 'bar'
113 | temp['name'] = console
114 | data.append(temp)
115 |
116 | layout = dict(title=title,
117 | xaxis={'title':'Consoles'},
118 | yaxis={'title':'Market Share (%)', 'range': [0,100]},
119 | barmode='group',
120 | transition={'duration': 500})
121 |
122 | return {'data': data, 'layout': layout}
123 |
124 | @app.callback([Output('vis','figure'), Output('markdown','children')],
125 | [Input('region-dropdown','value'),
126 | Input('type-radio','value')])
127 | def display_graph(region, vis_type):
128 | df_temp = df[df['Region']==region]
129 | fig = None
130 | vis_title = 'Gaming Market Share in 2018'
131 | if vis_type == 'line':
132 | fig = getLineChart(df_temp, vis_title)
133 | elif vis_type == 'bar':
134 | fig = getBarChart(df_temp, vis_title)
135 | filepath_markdown = 'Data/Markdown_'
136 | filepath_markdown += region2brief[region]
137 | filepath_markdown += '.txt'
138 | f = open(filepath_markdown, 'r')
139 | text = 'A brief analysis: '
140 | text += f.read()
141 | f.close()
142 | return fig, text
143 |
144 | if __name__ == '__main__':
145 | app.run_server(debug=True, port=1200)
--------------------------------------------------------------------------------
/DashboardExample/Data/Console_share_CA.csv:
--------------------------------------------------------------------------------
1 | "Date","Playstation","Xbox","Nintendo"
2 | 2018-01,63.56,31.12,5.32
3 | 2018-02,66.45,29.36,4.19
4 | 2018-03,67.63,28.35,4.02
5 | 2018-04,67.61,28.42,3.97
6 | 2018-05,66.91,29.47,3.61
7 | 2018-06,69.31,27.11,3.58
8 | 2018-07,69.3,26.79,3.91
9 | 2018-08,71.95,25.04,3
10 | 2018-09,71.68,25.07,3.25
11 | 2018-10,68.91,27.37,3.72
12 | 2018-11,65.51,31.15,3.34
13 | 2018-12,68.82,29.09,2.09
14 |
--------------------------------------------------------------------------------
/DashboardExample/Data/Console_share_GB.csv:
--------------------------------------------------------------------------------
1 | "Date","Playstation","Xbox","Nintendo","Other"
2 | 2018-01,57.31,41.18,1.51,0
3 | 2018-02,64.97,33.86,1.17,0
4 | 2018-03,67.57,31.28,1.15,0
5 | 2018-04,67.02,31.79,1.19,0
6 | 2018-05,64.97,33.91,1.12,0
7 | 2018-06,64.06,34.37,1.57,0
8 | 2018-07,63.79,35.05,1.17,0
9 | 2018-08,67.31,31.63,1.06,0
10 | 2018-09,69.36,29.41,1.23,0
11 | 2018-10,64.07,35.02,0.92,0
12 | 2018-11,60.95,38.25,0.8,0
13 | 2018-12,61.73,37.48,0.79,0
14 |
--------------------------------------------------------------------------------
/DashboardExample/Data/Console_share_HK.csv:
--------------------------------------------------------------------------------
1 | "Date","Playstation","Xbox","Nintendo"
2 | 2018-01,82.95,12.78,4.27
3 | 2018-02,85.59,10.85,3.56
4 | 2018-03,85.54,7.8,6.65
5 | 2018-04,88.31,4.83,6.85
6 | 2018-05,91.74,3.68,4.58
7 | 2018-06,90.96,4.68,4.35
8 | 2018-07,88.29,6.11,5.6
9 | 2018-08,91.73,5.53,2.74
10 | 2018-09,92.08,3.88,4.04
11 | 2018-10,87.97,7.97,4.06
12 | 2018-11,84.02,10.75,5.22
13 | 2018-12,83.61,10.94,5.45
14 |
--------------------------------------------------------------------------------
/DashboardExample/Data/Console_share_JP.csv:
--------------------------------------------------------------------------------
1 | "Date","Playstation","Nintendo","Xbox"
2 | 2018-01,75.59,21.95,2.47
3 | 2018-02,76.26,21.59,2.15
4 | 2018-03,75.19,22.99,1.82
5 | 2018-04,77.82,19.51,2.67
6 | 2018-05,77.85,17.1,5.05
7 | 2018-06,81.69,15.83,2.49
8 | 2018-07,78.48,19.28,2.24
9 | 2018-08,79.45,18.71,1.85
10 | 2018-09,83.92,13.47,2.6
11 | 2018-10,85.06,12.77,2.17
12 | 2018-11,84.91,12.75,2.34
13 | 2018-12,87.04,11.01,1.95
14 |
--------------------------------------------------------------------------------
/DashboardExample/Data/Console_share_KR.csv:
--------------------------------------------------------------------------------
1 | "Date","Playstation","Xbox","Nintendo"
2 | 2018-01,85.67,14.21,0.12
3 | 2018-02,90.98,8.5,0.52
4 | 2018-03,87.99,11.08,0.94
5 | 2018-04,90.07,8.7,1.23
6 | 2018-05,91.66,7.79,0.55
7 | 2018-06,86.95,9.99,3.06
8 | 2018-07,91.4,8.35,0.25
9 | 2018-08,86.72,13.15,0.14
10 | 2018-09,75.8,24,0.2
11 | 2018-10,78.81,20.94,0.25
12 | 2018-11,78.05,20.2,1.75
13 | 2018-12,74.69,21.27,4.05
14 |
--------------------------------------------------------------------------------
/DashboardExample/Data/Console_share_US.csv:
--------------------------------------------------------------------------------
1 | "Date","Playstation","Xbox","Nintendo"
2 | 2018-01,60.97,32.97,6.06
3 | 2018-02,63.4,31.04,5.56
4 | 2018-03,64.44,30.34,5.22
5 | 2018-04,65.3,29.27,5.43
6 | 2018-05,60.89,34.03,5.08
7 | 2018-06,60.17,34.83,5
8 | 2018-07,63.06,32.01,4.94
9 | 2018-08,67.5,28.14,4.36
10 | 2018-09,62.39,32.68,4.93
11 | 2018-10,61,34.56,4.44
12 | 2018-11,58.31,35.8,5.89
13 | 2018-12,59.88,35.9,4.22
14 |
--------------------------------------------------------------------------------
/DashboardExample/Data/Console_share_WorldWide.csv:
--------------------------------------------------------------------------------
1 | "Date","Playstation","Xbox","Nintendo","Other"
2 | 2018-01,70.51,25.9,3.59,0
3 | 2018-02,72.81,23.95,3.24,0
4 | 2018-03,72.57,24.27,3.16,0
5 | 2018-04,73.34,23.28,3.38,0
6 | 2018-05,70.59,26.14,3.27,0
7 | 2018-06,70.34,26.1,3.56,0
8 | 2018-07,70.19,26.28,3.53,0
9 | 2018-08,73.4,23.43,3.17,0
10 | 2018-09,73.14,23.87,3,0
11 | 2018-10,69.59,25.75,4.66,0
12 | 2018-11,65.37,27.22,7.41,0
13 | 2018-12,70.21,27.32,2.48,0
14 |
--------------------------------------------------------------------------------
/DashboardExample/Data/Markdown_CA.txt:
--------------------------------------------------------------------------------
1 | The market share of gaming console in Canada is similar to the market share in the US. Xbox has better co-op games and supports on online multi-player gaming. The loyality of PlayStation gamers helps PlayStation to maintain their market share status. The increase of exclusive and localization titles available to the Xbox platform will be the challenge to PlayStation market share.
--------------------------------------------------------------------------------
/DashboardExample/Data/Markdown_GB.txt:
--------------------------------------------------------------------------------
1 | The market share of gaming console in Great Britain is similar to the market share in the US. Xbox has better co-op games and supports on online multi-player gaming. The loyality of PlayStation gamers helps PlayStation to maintain their market share status. The increase of exclusive and localization titles available to the Xbox platform will be the challenge to PlayStation market share.
--------------------------------------------------------------------------------
/DashboardExample/Data/Markdown_HK.txt:
--------------------------------------------------------------------------------
1 | Hong Kong gamers have grown up with PlayStation consoles and Microsoft are struggle to change the gamers' console preference. Most of the Hong Kong gamers' games preference are mostly PlayStation exclusive, especially JRPG games. There are more exclusive shooting games available on the Xbox platform but Hong Kong gamers are more likely play shooting games on PC, so it did not help Microsoft to sell their Xbox.
--------------------------------------------------------------------------------
/DashboardExample/Data/Markdown_JP.txt:
--------------------------------------------------------------------------------
1 | Microsoft had a different time to promote their Xbox to the Japan gaming market due to their relationship with the game publishers. Due to Microsoft's unwelcomed relationship with game publishers resulted a lack of Japenese gamers' preferred games available in Japan, such as JRPG games. Most of the games Japanese gamers like were available in PlayStation and Nintendo platforms. As there are more PlayStation exclusive games available on the Xbox platform, we may see an mild increase in market share in Xbox.
--------------------------------------------------------------------------------
/DashboardExample/Data/Markdown_KR.txt:
--------------------------------------------------------------------------------
1 | Korean gamers have grown up with PlayStation and the exclusive games available on the PlayStation platform.
--------------------------------------------------------------------------------
/DashboardExample/Data/Markdown_US.txt:
--------------------------------------------------------------------------------
1 | The market share between PlayStation and Xbox are roughly more even than the market share in other regions. The design of the Xbox and the exclusive titles available on the Xbox platform were appealing to American gamers. The Xbox has done a better job on co-op gaming than its rivals, especially shooting games. However, the loyality of PlayStation gamers helps PlayStation to maintain their market share status. The increase of exclusive and localization titles available to the Xbox platform will be the challenge to PlayStation market share.
--------------------------------------------------------------------------------
/DashboardExample/Data/Markdown_WorldWide.txt:
--------------------------------------------------------------------------------
1 | The overall gaming console market share is dominated by PlayStation. Even the market share between Xbox and PlayStation is evenly shared in the Western world, but the PlayStation has a significantly larger share in Asian countries. The major reason is that there are more normal and exclusive titles available on the PlayStation platform than on the Xbox platform, especailly there are more partnership between Japanese game publishers and Sony. However, the online service provided by Microsoft has a better feedback than the service provided by Sony that help Microsoft to promote their Xbox to gamers for playing online co-op games.
--------------------------------------------------------------------------------
/DashboardExample/Data/source.txt:
--------------------------------------------------------------------------------
1 | http://gs.statcounter.com/os-market-share/console/hong-kong/2018
2 | https://gs.statcounter.com/os-market-share/console/united-states-of-america/2018
3 | https://gs.statcounter.com/os-market-share/console/united-kingdom/2018
4 | https://gs.statcounter.com/os-market-share/console/canada/2018
5 | https://gs.statcounter.com/os-market-share/console/japan/2018
6 | https://gs.statcounter.com/os-market-share/console/south-korea/2018
--------------------------------------------------------------------------------
/DashboardExample/Images/Dash@2x.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashboardExample/Images/Dash@2x.jpg
--------------------------------------------------------------------------------
/DashboardExample/Images/gaming_dashboard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashboardExample/Images/gaming_dashboard.png
--------------------------------------------------------------------------------
/DashboardExample/Images/gaming_dashboard_bar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashboardExample/Images/gaming_dashboard_bar.png
--------------------------------------------------------------------------------
/DashboardExample/Images/gaming_dashboard_layout.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/DashboardExample/Images/gaming_dashboard_layout.png
--------------------------------------------------------------------------------
/DashboardExample/Readme.md:
--------------------------------------------------------------------------------
1 | # Dashboard Example - Gaming Console Market Share in 2018
2 | The goal of this example is to use Plotly Dash to build a dashboard to display the gaming console market share in 2018 using the techniques learnt in Part 1,2,3.
3 |
4 | ## Background and Dashboard Design
5 | Fun fact: PlayStation sells way better in Asian market than the sales of Xbox. I want to develop a dashboard for users to display the gaming console market share in different region with a brief analysis.
6 |
7 | In this dashboard, I would like to have the users first to select region and the dashboard would update the visualization based on what region the users selected and display the brief analysis below the visualization.
8 |
9 | Therefore, the layout of this dashboard would be including a headline, background and description, region and visualization selections, visualization, and analysis.
10 |
11 | ## Files
12 | There is 1 python file, [DashExample](DashExample.py) and a folder of data, "Data Folder", including data set files in csv files and text files of market share analysis.
13 |
14 |
15 | In the python file, it defines how the dashboard is running. It consists 3 parts:
16 | * Read files and definition
17 | * Dashboard layout
18 | * Dashboard interaction
19 |
20 | In first part of the code, the program read all the data set in csv files in the Data Folder, define the options of the dropdown list and radio item list, headline, background and description.
21 |
22 | The second part is the core part of the program, the dashboard layout. In the layout, there are 5 components on the Dashboard:
23 | * H1, to display headline.
24 | * Div, to display background and description of the dashboard.
25 | * Div, which consists two Div's, each sub-Div is built to store dropdown list and radio item list. The dropdown list is built to select region, and the radio item list is built to select whether the user wants to display in line chart or bar chart.
26 | * Div, which consists a dcc.Graph() object with a id='vis' which render a Plotly visualization
27 | * Div, which consists a dcc.Markdown() to display the brief analysis
28 |
29 | The third part is defining the dashboard interaction. It consists of 3 functions:
30 | * display_graph()
31 | * getLineChart()
32 | * getBarChart()
33 |
34 | If the users have change the selection on the dropdown list or radio item list, display_graph() is called and return a new visualization. There are two parameters will be received when the function is called: the value of the dropdown list and the value of the radio item list, the values represent the region selection and the type of visualization selection, respectively. When the function is called, it would filter the data to the region selected and plot the visualization by calling either getLineChart() or getBarChart() whether either type of visualization is selected. The next step is to obtain the analysis by reading the analysis saved in the text file in the Data folder. Once the visualization and analysis are prepared, the function will return both objects to app.layout(). The visualization will be plotted on the div with id='vis', and the analysis will be display on the dcc.MarkDown().
35 |
36 | ## Result
37 | The dashboard looks like this:
38 |
39 |
40 |
41 | ## Source
42 | The below hyperlinks are the source of the data set:
43 | * http://gs.statcounter.com/os-market-share/console/hong-kong/2018
44 | * https://gs.statcounter.com/os-market-share/console/united-states-of-america/2018
45 | * https://gs.statcounter.com/os-market-share/console/united-kingdom/2018
46 | * https://gs.statcounter.com/os-market-share/console/canada/2018
47 | * https://gs.statcounter.com/os-market-share/console/japan/2018
48 | https://gs.statcounter.com/os-market-share/console/south-korea/2018
--------------------------------------------------------------------------------
/DockerizeDash/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.7.1
2 |
3 | WORKDIR /code
4 |
5 | COPY ./requirements.txt /code/requirements.txt
6 |
7 | RUN pip install --upgrade pip
8 | RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
9 |
10 | RUN pip uninstall --yes werkzeug
11 | RUN pip install -v https://github.com/pallets/werkzeug/archive/refs/tags/2.0.3.tar.gz
12 |
13 | COPY ./display_dash.py /code/display_dash.py
14 |
15 | CMD ["python","display_dash.py"]
16 |
--------------------------------------------------------------------------------
/DockerizeDash/display_dash.py:
--------------------------------------------------------------------------------
1 | import dash
2 | import dash_core_components as dcc
3 | import dash_html_components as html
4 |
5 |
6 | # Initiate App
7 | app = dash.Dash(__name__)
8 |
9 | # The layout of the dashboard
10 | app.layout = html.Div(children=[
11 | html.H1(children='''Example 1: Bar Chart with Single-malt
12 | Scotch Whisky Statistics'''),
13 |
14 | html.Div(children='''In here, we are counting distilleries
15 | per region and their whisky smokiness'''),
16 |
17 | dcc.Graph(
18 | id='example-graph', # Name this div
19 | figure={
20 | 'data': [
21 | {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
22 | {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
23 | ],
24 | 'layout': {
25 | 'title': 'Dash Data Visualization'
26 | }
27 | }
28 | ) # Position 2, children in Div
29 | ]) # End Div
30 |
31 | if __name__ == '__main__':
32 | app.run_server(debug=True, host='0.0.0.0', port=9000)
33 |
--------------------------------------------------------------------------------
/DockerizeDash/readme.md:
--------------------------------------------------------------------------------
1 | # Dockerize Dash
2 | This section contains the quick-start note for dockerizing Plotly and Dash for your solution. We would go over the tips on writing the Dockerfile and the dependent Python scripts.
3 |
4 | You may read the instructions in this Medium Post: Dockerizing Plotly/Dash
5 |
6 | ## Dockerfile
7 | Beside copying the scripts to the docker container, you would need to install the right version of dependencies in order to have Dash run properly. Here are the important note:
8 |
9 | - Beside Plotly and Dash, You must include flask v2.1.3
10 | - werkzeug must be v2.0.3 which is downloaded from this repository. It is also included in the Dockerfile
11 |
12 |
13 |
14 | ### Note on Python Scripts
15 | When initiate the Dash app object, the host must be set at 0.0.0.0 in order for the local environment to access the container environment.
16 |
17 | ```
18 | if __name__ == '__main__':
19 | app.run_server(debug=True, host='0.0.0.0', port=9000)
20 | ```
21 |
22 | Since we have set the port to 9000 here, the dashboard will be ran in port 9000 in the Container environment.
23 |
24 | ## How to Run?
25 | Once you have Dockerfile ready, then:
26 |
27 | - Build the docker image (Be sure to include "." for the Dockerfile path)
28 | - Run and create a docker container
29 | - Access the dashboard on your browser with the right port number
30 |
31 |
32 | See the code below, given we have declared port at 9000 in the container environment.
33 |
34 | ```
35 | # Build the docker image
36 | docker build -t [image_name] .
37 |
38 | # Run and create a docker container
39 | docker run -h localhost -p 9002:9000 -d --name [container_name] [image_name]
40 | ```
41 |
42 |
43 | In the code above, we have expose the dashboard at port 9000 in the local environment. It means once we access port 9000 in the local environment, it would redirect us to the port 9002 in the container environment.
44 |
45 | Note: This example we have set local machine port at 9002 and container port 9000 (According to the port declared in the Python script). You may choose other port number.
46 |
47 |
48 | ## Reference
49 | Troubleshoot Host Error Running dash app in docker container in the Plotly Community
50 |
51 | Troubleshoot Werkzeug Error Dash ImportError in Stack Overflow
--------------------------------------------------------------------------------
/DockerizeDash/requirements.txt:
--------------------------------------------------------------------------------
1 | dash==1.10.0
2 | dash-core-components==1.9.0
3 | dash-html-components==1.0.3
4 | dash-renderer==1.3.0
5 | dash-table==4.6.2
6 | flask==2.1.3
7 | plotly==4.14.3
8 |
--------------------------------------------------------------------------------
/Part1/README.md:
--------------------------------------------------------------------------------
1 | # Part 1: Basics of Using Dash
2 |
3 | ## Prequisite of using Dash
4 |
5 | - Knowing how Plotly works in Python
6 | - Knowing how Flask works in Python
7 | - Understand how html works
8 |
9 |
10 | ## Goals
11 | The goals of Part 1 are:
12 | 1. Understand the basic layout of Dash
13 | 2. Understand the basic of dcc and html packages
14 | 3. Graph a chart using figure in dcc.Graph()
15 | 4. Pass a previous Plotly graph on Dash
16 |
17 | ## Plotly Dash Example
18 | Reference here: Dash Layout
19 |
20 |
21 | app.py is the code copied from the plotly dash site for testing.
22 |
23 |
24 | Dash is very similar to using Flask on building a html. In this example, app.layout to outline the html page and build the Plotly figure on top of the html elements. The example on the Dash Layout site demostrates a higher level method to build bar chart on Dash.
25 |
26 |
27 | [dash_part1.py](dash_part1.py) is the file identical to app.py from the Dash Layout reference page.
28 |
29 | ## Example 1: Practice on my own
30 | Plotly Dash can be viewed as a high-level visuilazation tool hosted by Flask. To build a Plotly Dash dashboard, you have to declare an app object, which is a Flask object. Then, you will design the dashboard by adding html components or dash core components into the layout instance. Html components are basic html instance; dash core components (dcc) are Dash-built object to show graphs or other Dash objects. The layout instance of app is composed of a tree of compoents. In each html components or dcc consists of attributes to define content, graphs, or format. For example, if you put html.H1(chilren='Hello World!'), Dash will translate that to < H1>Hello World!< /H1> on a html file. The code is run, it renders the html as you have defined and hosted on Flask server.
31 |
32 | I used whisky.csv to plot a bar chart. You may find the data here. And the result looks like this:
33 |
34 |
35 |
36 |
37 | And the original Plotly graph looks like:
38 |
39 |
40 |
41 |
42 | ## Example 2: Using go.Figure on Dash
43 | Reference here: Plotly Figures on Dash
44 |
45 | If you know how to make a graph on Plotly and wish to host it on Dash. You may also do this. If you have existing code define the figure object in Plotly already, you may pass this figure object to dcc.Graph(), ie, you may define fig first, and pass fig to dcc.Graph(), dcc.Graph(figure=fig). It means you could define the figure instance outside of app.layout. In this example, I will use my existing Plotly graph and host it on Dash. The Plotly line chart is about the traffic of IPs given in the data set and was a homework I worked on my Data Visualization class in graduate school.
46 |
47 | The result looks like this:
48 |
49 |
50 | ## Notes
51 |
52 | - Dash's purpose is to build the visualization on a html page and host the html page on a Flask server.
53 | - Dash relies on Flask. Once you import Dash, it automatically import Flask. And the code is very similar to Flask.
54 | - app.layout lists the html page in hierarchical structure
55 | - You can either define figure outside or within app.layout. If you have done a visualization with Plotly before, you may just pass your previous Plotly figure into app.layout.
56 | - Flask host your html page at your localhost. To change port, add 'port=xxxx' as an arguement in app.run_server()
57 |
58 |
59 | ## Next Charter
60 | Clicker [here](../Part2) to advance to next chapter.
--------------------------------------------------------------------------------
/Part1/computer_security_dash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part1/computer_security_dash.png
--------------------------------------------------------------------------------
/Part1/dash_part1.py:
--------------------------------------------------------------------------------
1 | """
2 | This is the code from the Dash tutorial Part 2 - Layout
3 | """
4 | import dash
5 | import dash_core_components as dcc
6 | import dash_html_components as html
7 |
8 | # CSS Template
9 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
10 |
11 | # Flask app
12 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
13 |
14 | app.layout = html.Div(children=[ #id="_dash-app-content"
15 | html.H1(children='Hello Dash'), # Position 0, children in Div
16 |
17 | html.Div(children='''
18 | Dash: A web application framework for Python.
19 | '''), # Postion 1, children in Div (H1 is built on top of here)
20 |
21 | dcc.Graph(
22 | id='example-graph', # Name this div
23 | figure={
24 | 'data': [
25 | {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
26 | {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
27 | ],
28 | 'layout': {
29 | 'title': 'Dash Data Visualization'
30 | }
31 | }
32 | ) # Position 2, children in Div
33 | ])
34 |
35 | if __name__ == '__main__':
36 | app.run_server(debug=True)
37 |
--------------------------------------------------------------------------------
/Part1/example1_whisky.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import dash
3 | import dash_core_components as dcc
4 | import dash_html_components as html
5 |
6 |
7 | # Flask and html set up
8 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
9 | #app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
10 | app = dash.Dash(__name__)
11 |
12 |
13 | # Load the data
14 | data_path = "../../ScotchWhisky/Data/whisky.csv"
15 | whisky = pd.read_csv(data_path)
16 | """
17 | This is same as:
18 | select region, smoky, count(1)
19 | from data
20 | group by 1,2;
21 | """
22 | whisky = whisky.groupby(['Region','Smoky'])['Smoky'].count().reset_index(name='count')
23 | regions = whisky['Region'].unique()
24 | whisky_data = []
25 | for region in regions:
26 | temp = {}
27 | temp['x'] = whisky[whisky['Region']==region]['Smoky'].tolist()
28 | temp['y'] = whisky[whisky['Region']==region]['count'].tolist()
29 | temp['type'] = 'bar'
30 | temp['name'] = region
31 | whisky_data.append(temp)
32 |
33 | app.layout = html.Div(children=[
34 | html.H1(children='''Example 1: Bar Chart with Single-malt
35 | Scotch Whisky Statistics'''),
36 |
37 | html.Div(children='''In here, we are counting distilleries
38 | per region and their whisky smokiness'''),
39 |
40 | dcc.Graph(
41 | id='whisky-barchart',
42 | figure={
43 | 'data':whisky_data,
44 | 'layout':{'title': 'Smoky Single-malt Whiskies per Region',
45 | 'xaxis': {'title': 'Score of Smokiness'},
46 | 'yaxis': {'title': 'Count of Distilleries'}
47 | } # End Layout
48 | } # End figure
49 | ) # End Graph
50 | ]) # End Div
51 |
52 | if __name__=='__main__':
53 | app.run_server(debug=True, port=8051)
54 |
55 |
56 |
--------------------------------------------------------------------------------
/Part1/example2_existing_plotly.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import dash
3 | import plotly.graph_objs as go
4 | import dash_core_components as dcc
5 | import dash_html_components as html
6 | from datetime import datetime
7 |
8 | """
9 | This part is identical to the code for visualizating with Plotly.
10 | """
11 | # Read data
12 | data = pd.read_csv('data.csv')
13 | # Assign color to IPs
14 | ip_target = [(1, 'rgb(255,0,0)'), (3, 'rgb(93, 173, 226)'),
15 | (4, 'rgb(255, 215, 0)'), (5, 'rgb(230, 21, 192)'),
16 | (6, 'rgb(100, 127, 146)')]
17 |
18 | # Put data and meta data for line chart
19 | content = []
20 | for ip, color_choice in ip_target:
21 | temp_data = data.loc[data['l_ipn']==ip]
22 | temp = go.Scatter(x = temp_data.date,
23 | y = temp_data['sumtraffic'],
24 | name = 'IP '+ str(ip),
25 | line = dict(color = color_choice),
26 | opacity = 0.8)
27 | content.append(temp)
28 |
29 | shapes = []
30 | date_target = [datetime(2006, 8, 24), datetime(2006, 9, 4),
31 | datetime(2006, 9, 18), datetime(2006, 9, 26)]
32 |
33 | # Set fixed x-axis and y-axis and line color
34 | for i in date_target:
35 | shapes.append({'type': 'line',
36 | 'xref': 'x',
37 | 'yref': 'y',
38 | 'x0': i,
39 | 'y0': 0,
40 | 'x1': i,
41 | 'y1': 1000000,
42 | 'line': {'color': 'rgb(211, 211, 211)',
43 | 'width': 2,
44 | 'dash': 'dashdot'}})
45 |
46 | # Declare drop down list
47 | updatemenus = list([
48 | dict(active=-1,
49 | buttons=list([
50 | dict(label = 'All',
51 | method = 'update',
52 | args = [{'visible': [True, True, True, True, True]},
53 | {'title': 'Total Traffic of each IP per day'}]),
54 | dict(label = 'IP 1',
55 | method = 'update',
56 | args = [{'visible': [True, False, False, False, False]},
57 | {'title': 'Total Traffic of IP 1 per day'}]),
58 | dict(label = 'IP 3',
59 | method = 'update',
60 | args = [{'visible': [False, True, False, False, False]},
61 | {'title': 'Total Traffic of IP 3 per day'}]),
62 | dict(label = 'IP 4',
63 | method = 'update',
64 | args = [{'visible': [False, False, True, False, False]},
65 | {'title': 'Total Traffic of IP 4 per day'}]),
66 | dict(label = 'IP 5',
67 | method = 'update',
68 | args = [{'visible': [False, False, False, True, False]},
69 | {'title': 'Total Traffic of IP 5 per day'}]),
70 | dict(label = 'IP 6',
71 | method = 'update',
72 | args = [{'visible': [False, False, False, False, True]},
73 | {'title': 'Total Traffic of IP 6 per day'}])
74 | ]),
75 | )
76 | ])
77 |
78 | # Declare layout of the line chart
79 | layout = dict(title = 'Total Traffic of each IP per day',
80 | xaxis = dict(title = 'Date'),
81 | yaxis = dict(title = 'Total Traffic', type='log',
82 | range = [0, 6]),
83 | shapes = shapes, updatemenus = updatemenus)
84 |
85 | # Put all data and meta data into fig
86 | fig = dict(data = content, layout = layout)
87 |
88 | """
89 | This part is the code additional if visualizating with Dash
90 | """
91 | app = dash.Dash(__name__)
92 |
93 | app.layout = html.Div(children=[
94 | html.H1(children='Example 2: Plot a Plotly Graph Object on Dash'),
95 |
96 | html.Div(children='''
97 | In this example, we are going to make a line chart with Plotly first,
98 | and plot the graph object on Dash. The data is related to the traffic
99 | of certain IPs. You may filter the traffic to one IP by selecting on
100 | the drop-down list.
101 | '''),
102 |
103 | dcc.Graph(id='security-line-chart',figure=fig)
104 |
105 | ])
106 |
107 | if __name__=='__main__':
108 | app.run_server(debug=True, port=8052)
--------------------------------------------------------------------------------
/Part1/whisky_dash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part1/whisky_dash.png
--------------------------------------------------------------------------------
/Part1/whisky_plotly.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part1/whisky_plotly.png
--------------------------------------------------------------------------------
/Part2/dash_inputs.py:
--------------------------------------------------------------------------------
1 | import dash
2 | import dash_core_components as dcc
3 | import dash_html_components as html
4 | from dash.dependencies import Input, Output
5 |
6 | import pandas as pd
7 |
8 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
9 |
10 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
11 |
12 | df = pd.read_csv('https://plotly.github.io/datasets/country_indicators.csv')
13 |
14 | available_indicators = df['Indicator Name'].unique()
15 |
16 | app.layout = html.Div([
17 | html.Div([
18 |
19 | html.Div([
20 | dcc.Dropdown(
21 | id='xaxis-column',
22 | options=[{'label': i, 'value': i} for i in available_indicators],
23 | value='Fertility rate, total (births per woman)'
24 | ),
25 | dcc.RadioItems(
26 | id='xaxis-type',
27 | options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
28 | value='Linear',
29 | labelStyle={'display': 'inline-block'}
30 | )
31 | ],
32 | style={'width': '48%', 'display': 'inline-block'}),
33 |
34 | html.Div([
35 | dcc.Dropdown(
36 | id='yaxis-column',
37 | options=[{'label': i, 'value': i} for i in available_indicators],
38 | value='Life expectancy at birth, total (years)'
39 | ),
40 | dcc.RadioItems(
41 | id='yaxis-type',
42 | options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
43 | value='Linear',
44 | labelStyle={'display': 'inline-block'}
45 | )
46 | ],style={'width': '48%', 'float': 'right', 'display': 'inline-block'})
47 | ]),
48 |
49 | dcc.Graph(id='indicator-graphic'),
50 |
51 | dcc.Slider(
52 | id='year--slider',
53 | min=df['Year'].min(),
54 | max=df['Year'].max(),
55 | value=df['Year'].max(),
56 | marks={str(year): str(year) for year in df['Year'].unique()},
57 | step=None
58 | )
59 | ])
60 |
61 | @app.callback(
62 | Output('indicator-graphic', 'figure'),
63 | [Input('xaxis-column', 'value'),
64 | Input('yaxis-column', 'value'),
65 | Input('xaxis-type', 'value'),
66 | Input('yaxis-type', 'value'),
67 | Input('year--slider', 'value')])
68 | def update_graph(xaxis_column_name, yaxis_column_name,
69 | xaxis_type, yaxis_type,
70 | year_value):
71 | dff = df[df['Year'] == year_value]
72 |
73 | return {
74 | 'data': [dict(
75 | x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],
76 | y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
77 | text=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'],
78 | mode='markers',
79 | marker={
80 | 'size': 15,
81 | 'opacity': 0.5,
82 | 'line': {'width': 0.5, 'color': 'white'}
83 | }
84 | )],
85 | 'layout': dict(
86 | xaxis={
87 | 'title': xaxis_column_name,
88 | 'type': 'linear' if xaxis_type == 'Linear' else 'log'
89 | },
90 | yaxis={
91 | 'title': yaxis_column_name,
92 | 'type': 'linear' if yaxis_type == 'Linear' else 'log'
93 | },
94 | margin={'l': 40, 'b': 40, 't': 10, 'r': 0},
95 | hovermode='closest'
96 | )
97 | }
98 |
99 |
100 | if __name__ == '__main__':
101 | app.run_server(debug=True, port=8049)
--------------------------------------------------------------------------------
/Part2/dash_slider.py:
--------------------------------------------------------------------------------
1 | import dash
2 | import dash_core_components as dcc
3 | import dash_html_components as html
4 | from dash.dependencies import Input, Output
5 |
6 | import pandas as pd
7 |
8 |
9 | df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
10 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
11 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
12 |
13 | app.layout = html.Div([
14 | dcc.Graph(id='graph-with-slider'),
15 | dcc.Slider(
16 | id='year-slider',
17 | min=df['year'].min(), # Min of slidebar
18 | max=df['year'].max(), # Max of slidebar
19 | value=df['year'].min(), # Default value on the slidebar
20 | marks={str(year): str(year) for year in df['year'].unique()},
21 | # Marks on the slidebar
22 | step=None
23 | )
24 | ])
25 |
26 |
27 | @app.callback(
28 | Output('graph-with-slider', 'figure'),
29 | # Return element will feed figure input in dcc.Graph
30 | [Input('year-slider', 'value')]) # Input value
31 | def update_figure(selected_year):
32 | filtered_df = df[df.year == selected_year]
33 | traces = [] # Each continent assign to one bucket
34 | for i in filtered_df.continent.unique():
35 | df_by_continent = filtered_df[filtered_df['continent'] == i]
36 | traces.append(dict(
37 | x=df_by_continent['gdpPercap'],
38 | y=df_by_continent['lifeExp'],
39 | text=df_by_continent['country'],
40 | mode='markers',
41 | opacity=0.7,
42 | marker={
43 | 'size': 15,
44 | 'line': {'width': 0.5, 'color': 'white'}
45 | },
46 | name=i
47 | ))
48 |
49 | return {
50 | 'data': traces,
51 | 'layout': dict(
52 | xaxis={'type': 'log', 'title': 'GDP Per Capita',
53 | 'range':[2.3, 4.8]},
54 | yaxis={'title': 'Life Expectancy', 'range': [20, 90]},
55 | margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
56 | legend={'x': 0, 'y': 1},
57 | hovermode='closest',
58 | transition = {'duration': 500},
59 | )
60 | }
61 |
62 |
63 | if __name__ == '__main__':
64 | app.run_server(debug=True)
--------------------------------------------------------------------------------
/Part2/dash_slider_pic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part2/dash_slider_pic.png
--------------------------------------------------------------------------------
/Part2/example3_cap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part2/example3_cap.png
--------------------------------------------------------------------------------
/Part2/example3_slider.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import dash
3 | import dash_core_components as dcc
4 | import dash_html_components as html
5 | from dash.dependencies import Input, Output
6 |
7 | # Read file and split period into year and month
8 | data = pd.read_csv('Air_Traffic_Passenger_Statistics.csv')
9 | data['Activity Period'] = data['Activity Period'].astype(str)
10 | data['Year'] = data['Activity Period'].str[:4].astype(int)
11 | data['Month'] = data['Activity Period'].str[5:].astype(int)
12 |
13 | # Select columns
14 | selected_column = 'GEO Summary'
15 | data = data[['Published Airline','Year','Month','Passenger Count',
16 | 'GEO Region',selected_column]]
17 |
18 | # Declare Dash properties
19 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
20 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
21 |
22 | # Layout is headline, description, graph, and slider
23 | app.layout = html.Div([
24 | html.H1(children='Example 3: Slider'),
25 | html.Div(html.P(['''
26 | This example demostrates how to use slider on the dashboard.''',
27 | html.Br(),
28 | '''
29 | The chart display the observation of passenger traffic of
30 | each airline flying from/to a region in each month in a year.
31 | The slider control the year.''',
32 | html.Br(),
33 | '''
34 | This is not a good chart to visualize the data but the purpose
35 | is to build a slider on this dashboard.'''
36 | ])),
37 | dcc.Graph(id='graph-output'),
38 | dcc.Slider(
39 | id='year-slider',
40 | min=data['Year'].min(),
41 | max=data['Year'].max(),
42 | value=data['Year'].min()+1,
43 | marks={str(year): str(year) for year in data['Year'].unique()},
44 | step=None
45 | ) # End Slider
46 | ]) # End Div
47 |
48 | # @app.callback is defined for the below function
49 | @app.callback(
50 | Output('graph-output','figure'),[Input('year-slider','value')])
51 | def update_figure(selected_year):
52 | # Filter the year selected in slider
53 | df_filtered = data[data['Year']==selected_year]
54 | # Each element in traces is for one value in selected_column
55 | # Each value will be displayed as different colour
56 | traces = []
57 | for summ in df_filtered[selected_column].unique():
58 | # Filter data points in filtered year and selected_column
59 | df_filtered_temp = df_filtered[df_filtered[selected_column]==summ]
60 | traces.append(dict(
61 | x=df_filtered_temp['Month'],
62 | y=df_filtered_temp['Passenger Count'],
63 | text=df_filtered_temp['Published Airline']+': Flying from/to '+\
64 | df_filtered_temp['GEO Region'],
65 | mode='markers',
66 | marker={
67 | 'size': 15,
68 | 'line': {'width': 0.5, 'color': 'white'}
69 | },
70 | name=summ
71 | ))
72 |
73 | # return all info for figure
74 | return {
75 | 'data': traces,
76 | 'layout': dict(
77 | xaxis={'title': 'Month'},
78 | yaxis={'title': 'Passenger Count', 'type': 'log'},
79 | legend={'x':0, 'y': 0}, # Legend in bottom left
80 | hovermode='closest',
81 | transition= {'duration': 200}
82 | )
83 | }
84 |
85 | if __name__ == '__main__':
86 | app.run_server(debug=True, port=8051)
87 |
--------------------------------------------------------------------------------
/Part2/example4_cap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part2/example4_cap.png
--------------------------------------------------------------------------------
/Part2/example4_filter1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part2/example4_filter1.png
--------------------------------------------------------------------------------
/Part2/example4_multinput.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import dash
3 | import dash_core_components as dcc
4 | import dash_html_components as html
5 | from dash.dependencies import Input, Output
6 |
7 |
8 | # Read file and manipulate data
9 | data = pd.read_csv('Air_Traffic_Passenger_Statistics.csv')
10 | data['Activity Period'] = data['Activity Period'].astype(str)
11 | data['Year'] = data['Activity Period'].str[:4].astype(int)
12 | data['Month'] = data['Activity Period'].str[5:].astype(int)
13 | selected_column = 'GEO Summary'
14 |
15 | # Dash Set up
16 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
17 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
18 |
19 | # Options Set up
20 | terminal_options = [{'label': i, 'value': i} for i in data['Terminal'].unique()]
21 | terminal_options.append({'label': 'All', 'value': '*'})
22 | terminal_options.sort(key=lambda x: x['label']) # Sort dropdown list label
23 | geo_summ_options = [{'label': i, 'value': i} for i in
24 | data['GEO Summary'].unique()]
25 | geo_summ_options.append({'label': 'All', 'value': '*'})
26 | geo_summ_options.sort(key=lambda x: x['label']) # Sort radio list label
27 |
28 | app.layout = html.Div([
29 | html.H1(children='Example 4: Multiple Input'),
30 | # Layout Position 0, headline
31 | html.Div(html.P(['''
32 | This example demostrates how to pass two inputs to the visualization.
33 | ''',
34 | html.Br(),
35 | '''
36 | This example is the same as example 3 but adding two more filters.
37 | ''',
38 | html.Br(),
39 | '''
40 | There are a lot of violation on data visualization rules, but
41 | the purpose of this example is to demostrate the functionalities.
42 | Sorry for the inconvenience.
43 | '''
44 | ])), # Layout Position 1, description
45 | html.Div([
46 | html.Div([
47 | dcc.Dropdown(
48 | id='terminal-dropdown',
49 | options=terminal_options,
50 | value='*'
51 | ) # End drop down
52 | ], style={'width':'40%', 'display': 'inline-block'}),
53 | html.Div([
54 | dcc.RadioItems(
55 | id='geo-summary-radio',
56 | options=geo_summ_options,
57 | value='*'
58 | )# End Ratio items
59 | ], style={'width':'40%', 'display': 'inline-block'})
60 | # 'display' : 'inline-block' forces two div to be parallel
61 | ]), # End input Div
62 | # Layout Position 2, Input options
63 |
64 | dcc.Graph(id='vis'), # Layout Position 3, graph
65 |
66 | dcc.Slider(
67 | id='year-slider',
68 | min=data['Year'].min(),
69 | max=data['Year'].max(),
70 | value=data['Year'].min()+1,
71 | marks={str(year): str(year) for year in data['Year'].unique()},
72 | step=None
73 | ) # Layout Position 4, slider
74 |
75 | ]) # End outter Div
76 |
77 |
78 | # Obtain 3 inputs from two dropdown lists and slider to produce one graph
79 | @app.callback(
80 | Output('vis', 'figure'),
81 | [Input('terminal-dropdown','value'), Input('geo-summary-radio','value'),
82 | Input('year-slider','value')])
83 | def update_figure(terminal, geo_summ, selected_year):
84 | df_filtered = data[data['Year']==selected_year]
85 | if geo_summ != '*':
86 | df_filtered = df_filtered[df_filtered['GEO Summary']==geo_summ]
87 | if terminal != '*':
88 | df_filtered = df_filtered[df_filtered['Terminal']==terminal]
89 |
90 | traces = []
91 | for summ in df_filtered[selected_column].unique():
92 | df_filtered_temp = df_filtered[df_filtered[selected_column]==summ]
93 | traces.append(dict(
94 | x=df_filtered_temp['Month'],
95 | y=df_filtered_temp['Passenger Count'],
96 | text=df_filtered_temp['Published Airline']+': Flying from/to '+\
97 | df_filtered_temp['GEO Region'] + ' (' +
98 | df_filtered['Terminal'] + ')',
99 | mode='markers',
100 | marker={
101 | 'size': 15,
102 | 'line': {'width': 0.5, 'color': 'white'}
103 | },
104 | name=summ
105 | ))
106 |
107 | return {
108 | 'data': traces,
109 | 'layout': dict(
110 | xaxis={'title': 'Month'},
111 | yaxis={'title': 'Passenger Count', 'type': 'log'},
112 | legend={'x':0, 'y': 0},
113 | hovermode='closest',
114 | transition= {'duration': 200}
115 | )
116 | }
117 |
118 | if __name__ == '__main__':
119 | app.run_server(debug=True, port=8052)
120 |
--------------------------------------------------------------------------------
/Part2/example5_cap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part2/example5_cap.png
--------------------------------------------------------------------------------
/Part2/example5_multioutputs.py:
--------------------------------------------------------------------------------
1 | import dash
2 | import dash_core_components as dcc
3 | import dash_html_components as html
4 | from dash.dependencies import Input, Output
5 |
6 |
7 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
8 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
9 |
10 | options = ['Weight','Length','Volume']
11 | unit_options = ['Imperial','Metrics']
12 |
13 |
14 | app.layout = html.Div([
15 | html.H1(children='''
16 | Example 5: Multiple Inputs, Multiple Outputs, and State
17 | '''), # Layout position 0, headline
18 |
19 | html.Div(html.P(['''
20 | This example demostrates multiple outputs, chained callbacks,
21 | and State.
22 | ''',
23 | html.Br(),
24 | '''
25 | In this example, you may use this for converting units. Select
26 | your desired metrics and types. Then, enter the number and it
27 | will convert to other units.
28 | '''
29 |
30 | ])), # Position 1, description
31 |
32 | html.Div([
33 | dcc.RadioItems(
34 | id='unit-radio',
35 | options=[{'label': unit, 'value':unit} for unit in
36 | unit_options],
37 | value=unit_options[0]),
38 | html.Hr(),
39 | dcc.RadioItems(
40 | id='options-radio',
41 | options=[{'label': choice, 'value':choice} for choice
42 | in options],
43 | value=options[0]),
44 | html.Hr()
45 |
46 | ]), # Position 2, inputs
47 |
48 |
49 |
50 | html.Div(id='state-div'), # Position 4, State
51 |
52 | html.Br(), html.Br(),
53 |
54 | html.Div(children='''
55 | Please enter a number in the below text box:
56 | '''), # Position 5, instruction to enter initial value
57 |
58 | dcc.Input(id='input-textbox', value='', type='text'),
59 | # Position 6, textbox input
60 |
61 | html.Hr(),
62 |
63 | html.Div([
64 | html.Table([
65 | html.Tr([html.Td('It is equivalent to: '),
66 | html.Td(id='input-val-neg')]),
67 | html.Tr([html.Td('The initial value:'),html.Td(id='input-val')]),
68 | html.Tr([html.Td('It is equivalent to: '),
69 | html.Td(id='input-val-plus1')])
70 | ]) # End table
71 |
72 | ]) # Position 7, output in Table
73 |
74 | ]) # End Outer Div
75 |
76 | # Display the state
77 | @app.callback(Output('state-div','children'),
78 | [Input('unit-radio','value'), Input('options-radio','value')])
79 | def update_state(selected_metric, selected_type):
80 | return 'You have selected %s in %s.'%(selected_type, selected_metric)
81 |
82 | @app.callback([Output('input-val-neg','children'),
83 | Output('input-val','children'),
84 | Output('input-val-plus1','children')],
85 | [Input('unit-radio','value'),
86 | Input('options-radio','value'),
87 | Input('input-textbox','value')
88 | ])
89 | def calculate(selected_metric, selected_type, inti_val):
90 | input_val_neg, input_val, input_val_1 = (None, None, None)
91 | if inti_val == '':
92 | inti_val = 1
93 | else:
94 | # The value entered in textbox is string, convert to number
95 | inti_val = float(inti_val)
96 |
97 | if selected_type == 'Weight':
98 | if selected_metric == 'Imperial':
99 | input_val_neg = f'{inti_val*16:.2f} oz'
100 | input_val = f'{inti_val:.2f} lbs'
101 | input_val_1 = f'{inti_val/2240:.4f} tons'
102 | elif selected_metric == 'Metrics':
103 | input_val_neg = f'{inti_val*1000:.2f} grams'
104 | input_val = f'{inti_val:.2f} kilograms'
105 | input_val_1 = f'{inti_val/1000:.4f} metric tons'
106 |
107 | elif selected_type == 'Length':
108 | if selected_metric == 'Imperial':
109 | input_val_neg = f'{inti_val*5280:.2f} feet'
110 | input_val = f'{inti_val:.2f} miles'
111 | input_val_1 = f'{inti_val*1760:.2f} yards'
112 | elif selected_metric == 'Metrics':
113 | input_val_neg = f'{inti_val*1000:.2f} meters'
114 | input_val = f'{inti_val:.2f} kilometers'
115 | input_val_1 = f'{inti_val*100000:.2f} centimeters'
116 |
117 | elif selected_type == 'Volume':
118 | if selected_metric == 'Imperial':
119 | input_val_neg = f'{inti_val*16:.2f} cups'
120 | input_val = f'{inti_val:.2f} gals'
121 | input_val_1 = f'{inti_val*4:.2f} quarts'
122 | elif selected_metric == 'Metrics':
123 | input_val_neg = f'{inti_val*1000:.2f} mL'
124 | input_val = f'{inti_val:.2f} L'
125 | input_val_1 = f'{inti_val/1000:.4f} Cubic metre'
126 |
127 | return input_val_neg, input_val, input_val_1
128 |
129 |
130 | if __name__ == '__main__':
131 | app.run_server(debug=True, port=8053)
--------------------------------------------------------------------------------
/Part2/example5_output.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part2/example5_output.png
--------------------------------------------------------------------------------
/Part2/example6_markdown.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 | import dash
3 | import dash_core_components as dcc
4 | import dash_html_components as html
5 |
6 |
7 | # Declare Dash properties
8 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
9 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
10 |
11 | num = randint(1,11)
12 | num2 = randint(11,21)
13 | my_github = 'https://github.com/jacquessham'
14 | text = '''
15 | # Let's draw two random numbers!
16 | Let's draw a number between 1 and 10, and a number between
17 | 11 and 20.
18 | ## Draw a number between 1 and 10
19 | Between 1 and 10, I have drawn a {}.
20 | ## Draw a number between 11 and 20
21 | Between 11 and 20, I have drawn a {}.
22 | ## External site
23 | Free feel to visit my [Github]({})
24 | '''.format(num, num2, my_github)
25 | # In Dash markdown,
does not work, simply put extra nextline
26 |
27 |
28 | app.layout = html.Div([
29 | html.H1(children='Example 6: Markdown'), # Position 0, headline
30 | html.P('''
31 | This example demostrates how to use markdown in Dash.
32 | '''), # Position 1, description
33 | html.Hr(),
34 | dcc.Markdown(text) # Position 2, markdown
35 | ])
36 |
37 | if __name__ == '__main__':
38 | app.run_server(debug=True, port=8054)
--------------------------------------------------------------------------------
/Part2/example_filter2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part2/example_filter2.png
--------------------------------------------------------------------------------
/Part3/example7_hover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part3/example7_hover.png
--------------------------------------------------------------------------------
/Part3/example7_interactive.py:
--------------------------------------------------------------------------------
1 | import json
2 | from random import randint
3 | import dash
4 | import dash_core_components as dcc
5 | import dash_html_components as html
6 | from dash.dependencies import Input, Output
7 |
8 |
9 | # Declare Dash properties
10 | external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
11 | app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
12 |
13 | styles = {
14 | 'pre': {
15 | 'border': 'thin lightgrey solid',
16 | 'overflowX': 'scroll'
17 | }
18 | }
19 |
20 | # Define how does the graph looks like
21 | fig = {
22 | 'data':[
23 | {
24 | 'x': [randint(0,1000)/100.0 for i in range(4)],
25 | 'y': [randint(0,500)/100.0 for i in range(4)],
26 | 'text': ['alpha','bravo','charlie','delta'],
27 | 'name': '1st Category',
28 | 'mode': 'markers',
29 | 'marker': {'size': 12}
30 | },
31 | {
32 | 'x': [randint(200,600)/100.0 for i in range(4)],
33 | 'y': [randint(400,900)/100.0 for i in range(4)],
34 | 'text': ['papa','quebec','romeo','sierra'],
35 | 'name': '2nd Category',
36 | 'mode': 'markers',
37 | 'marker': {'size': 16}
38 | }
39 | ], # End data
40 | 'layout': {'clickmode': 'event+select'}
41 | }
42 |
43 |
44 | # Define the layout of the graph
45 | app.layout = html.Div([
46 | html.H1(children='Example 7: Interactive Visualization'),
47 | # Position 0, headline
48 | html.P('''
49 | This example demostrates the interactive functionality in Dash.
50 | '''), # Position 1, description
51 | html.Hr(),
52 | dcc.Graph(
53 | id='vis',
54 | figure=fig
55 | ), # End Graph
56 | # Position 2, graph
57 | html.Pre(id='hover-data',style=styles['pre']), # Position 3, hover textbox
58 | html.Pre(id='click-data',style=styles['pre']),
59 | # Position 4, textbox displays clicked data point
60 | html.Pre(id='click-datas',style=styles['pre']),
61 | # Position 4, textbox displays clicked 1+ data point
62 | ])
63 |
64 |
65 | @app.callback(Output('hover-data','children'),[Input('vis','hoverData')])
66 | def display_hoverdata(hoverdata):
67 | # If nothing is hover, it would throw an error
68 | if hoverdata is None:
69 | return None
70 | temp = hoverdata['points'][0]
71 | x = temp['x']
72 | y = temp['y']
73 | text = temp['text']
74 | message = '''
75 | The data point is ({},{}) and the text is {}
76 | '''.format(x, y, text)
77 | return message
78 |
79 | # This interaction only works on one data point
80 | @app.callback(Output('click-data','children'),[Input('vis','clickData')])
81 | def display_clickeddata(clickeddata):
82 | # If nothing is clicked, it also would throw an error
83 | if clickeddata is None:
84 | return None
85 | temp = clickeddata['points'][0]
86 | x = temp['x']
87 | y = temp['y']
88 | text = temp['text']
89 | message = '''
90 | You have clicked ({},{}) which the text is {}
91 | '''.format(x, y, text)
92 | return message
93 |
94 | # This interaction works for more than one data point
95 | @app.callback(Output('click-datas','children'),[Input('vis','selectedData')])
96 | def display_clickeddata(clickeddata):
97 | # If nothing is clicked, it prevents displaying null
98 | if clickeddata is None:
99 | return ''
100 | x = []
101 | y = []
102 | texts = []
103 | points = clickeddata['points']
104 | for point in points:
105 | x.append(point['x'])
106 | y.append(point['y'])
107 | texts.append(point['text'])
108 | pairs = ['('+str(x)+','+str(y)+')' for x,y in zip(x,y)]
109 | pairs = ','.join(pairs)
110 | texts = ', '.join(texts)
111 | message = '''
112 | You have clicked {} that the text are {}
113 | '''.format(pairs, texts)
114 | return message
115 |
116 | if __name__ == '__main__':
117 | app.run_server(debug=True, port=8051)
--------------------------------------------------------------------------------
/Part3/example7_selections.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/Part3/example7_selections.png
--------------------------------------------------------------------------------
/Part3/readme.md:
--------------------------------------------------------------------------------
1 | # Part 3: Interactive Visualization
2 |
3 | ## Last Chapter
4 | Click [here](../Part2) to go back to the last chapter.
5 |
6 | ## Goals
7 | In this chapter, we are going over interactive graphing in Dash. The goals of Part 3 are:
8 | 1. Display detail data when hovering data point on the graph.
9 | 2. Display detail data when selecting one data point on the graph.
10 | 3. Display detail data when selecting multiple points on the graph.
11 |
12 | You may find the reference [here](https://dash.plotly.com/interactive-graphing)
13 |
14 | ## Example 7: Interactive Visualization
15 | Displaying detail data when hovering or selecting data point on the graph is similar to selecting on slider or dropdown list. As usual, the first step is to set up the html component to display the detail of the of hovered or selected data. Then, set up the function to update as usual. However, under input, instead of obtaining 'value' from the component property, pass 'hoverData' for Hovering, 'clickData' for selecting one data point, or 'selectedData' for selecting multiple data points in Input.
16 | The example randomly plotly 8 data points on the Scatter plot and allow user to hover or select data point if the user wishes to learn more about it. Once the data point is hovered or selected, the detail would be displayed below the Scatter plot: The first Pre displays hovering data, the second Pre displays selected data (One data point only. Every click override the selection.), the third Pre displays selected data points (It looks similar to the second Pre if only one data point selected. If more than 1 data point selected, all data point detail would be displayed). If the user wishes to select more than one point. Press "Shift" when selecting more than 1 data point. If selecting data point without pressing "Shift", the selection would be overrided.
17 | The code example may be found [here](example7_interactive.py)
18 |
19 | The dashboard looks like this when the user hovers over a data point:
20 |
21 |
22 | If more than one data point is selected, the dashboard looks like this:
23 |
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/Groupbar.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/expense_everybody.csv')
11 | df = df.groupby(['name','expense_category'])['amount'].sum().reset_index()
12 | # Round number for amount column
13 | df['amount'] = df['amount'].round(2)
14 | # Colours for the category
15 | colours = ['green','black']
16 | # Bar Width
17 | widths = [0.5,0.25]
18 |
19 | # Prepare data
20 | data =[]
21 | for cate, colour, width in zip(df['expense_category'].unique(),colours, widths):
22 | df_temp = df[df['expense_category']==cate]
23 | data.append(go.Bar(name=cate,
24 | x=df_temp['name'], y=df_temp['amount'],
25 | marker_color=colour,
26 | width=[width]*len(df_temp['name']),
27 | text=df_temp['amount'], textposition='auto',
28 | textfont={'color':'white'}))
29 |
30 | fig_title = 'Everybody\'s Expense'
31 | layout = dict(title={'text':fig_title, 'x':0.5},
32 | barmode='group',
33 | xaxis=dict(tickmode='linear',tickangle=-45))
34 |
35 | fig = go.Figure(data=data, layout=layout)
36 |
37 | plotly.offline.plot(fig, filename='groupbar.html')
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/HorizontalBar.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Bar(y=df['name'], x=df['salary'],
15 | text=df['salary'], textposition='auto',
16 | orientation='h',
17 | textfont=dict(color='white')))
18 | # Layout
19 | layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5}}
20 |
21 | fig = go.Figure(data=data, layout=layout)
22 |
23 | plotly.offline.plot(fig, filename='hbar.html')
24 |
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/Simplebar.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Bar(x=df['name'], y=df['salary'],
15 | text=df['salary'], textposition='auto',
16 | textfont=dict(color='white')))
17 | # Layout
18 | layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5}}
19 |
20 | fig = go.Figure(data=data, layout=layout)
21 |
22 | plotly.offline.plot(fig, filename='bar.html')
23 |
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/Stackbar.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/expense_everybody.csv')
11 | df = df.groupby(['name','expense_category'])['amount'].sum().reset_index()
12 | # Round number for amount column
13 | df['amount'] = df['amount'].round(2)
14 |
15 | # Prepare data
16 | data =[]
17 | for cate in df['expense_category'].unique():
18 | df_temp = df[df['expense_category']==cate]
19 | data.append(go.Bar(name=cate,
20 | x=df_temp['name'], y=df_temp['amount'],
21 | text=df_temp['amount'], textposition='auto',
22 | textfont=dict(color='white')))
23 |
24 | fig_title = 'Everybody\'s Expense'
25 | layout = dict(title={'text':fig_title, 'x':0.5},
26 | barmode='stack',
27 | xaxis=dict(tickmode='linear',categoryorder='total descending'))
28 |
29 | fig = go.Figure(data=data, layout=layout)
30 |
31 | plotly.offline.plot(fig, filename='stackbar.html')
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/bar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/BarChart/bar.png
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/groupbar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/BarChart/groupbar.png
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/hbar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/BarChart/hbar.png
--------------------------------------------------------------------------------
/PlotlyExample/BarChart/stackbar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/BarChart/stackbar.png
--------------------------------------------------------------------------------
/PlotlyExample/BoxPlot/Readme.md:
--------------------------------------------------------------------------------
1 | # Box Plots
2 | Box Plots are plots to display the statistics of the given data, including median, quartiles, sometimes mean, and even outliers. In this folder, we will go over how to create box plots with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
9 |
10 | ## Pacakges Needed
11 | This chapter requires the following packages for the scripts used:
12 |
13 | - Pandas
14 | - Plotly
15 |
16 |
17 | ## Data Used
18 | This chapter may use the following data from the [Data folder](../Data):
19 |
22 |
23 | ## Syntax
24 | ### Data
25 | Data is a list of go.Box(), each go.Box() represents an attribute. If the data list has only 1 go.Box(), there is only 1 attribute (Only 1 box bar presents).
26 |
27 | go.Box() has the following parameters:
28 |
29 | - x: Value on x-axis (Horizontal Box Plot, if used, y should be empty)
30 | - y: Value on y-axis (Vertical Box Plot, if used, x should be empty)
31 | - name: Attribute, it will be represented as 1 box bar and displayed on x-axis
32 | - marker_color: Box bar colour (Take colour spelliing in string or RGB in string)
33 | - quartilemethod: The method to calculate quartile, takes only linear, inclusive, and exclusive
34 | - boxmean: Parameter whether the mean is presented on the chart, takes only True and False, default as False
35 | - boxpoints: What data point is plotted, takes only all, outliers, suspectedoutliers, and False
36 | - jitter: Space created to separate data points and box bars, takes between 0 and 1
37 | - pointpos: Relative position of points wrt box
38 |
39 |
40 |
41 |
42 | ### Layout
43 | Genetic Layout parameters suggested to use:
44 |
45 | - title (Dictionary): Chart title and fonts
46 |
47 | - text: Chart title to be displayed
48 | - x: text location on x-dimension, from 0-1
49 | - y: text location on y-dimension, from 0-1
50 |
51 | - xaxis (Dictionary): X-axis setting
52 |
53 | - tickmode: Setting of ticks
54 |
55 | - yaxis (Dictionary): y-axis setting
56 |
57 | - tickmode: Setting of ticks
58 |
59 | - boxmode: Use group to group together boxes of different traces
60 |
61 |
62 | Box Plot Exclusive parameters:
63 |
64 | - boxmean: Parameter whether the mean is presented on the chart
65 | - boxpoints: What data point is plotted, takes only all, outliers, suspectedoutliers, and False
66 | - jitter: Space created to separate data points and box bars, takes between 0 and 1
67 | - pointpos: Relative position of points wrt box
68 | - boxmode: Use group to group together boxes of different traces
69 |
70 |
71 | ### Syntax Difference with Bar Chart
72 | One difference between box plot and bar chart is syntax used for attribute and values. In box plot's go.Box(), name is used for attribute while either x or y is used for values. Note that, no error will be threw if both x and y are passed with values. However, it does not display the proper box plot as desired. Therefore, only pass the values with x or y, never pass both parameters (Meaning: Only use y and name if you want vertical box plot or use x and name if you want horizontal box plot)
73 |
74 | ## Example - Simple Box Plot
75 |
76 |
77 | ```
78 | # Prepare data
79 | data = []
80 | for school in df['school'].unique():
81 | df_temp = df[df['school']==school]
82 | data.append(go.Box(y=df_temp['salary'], name=school, boxmean=True))
83 |
84 | # Layout
85 | layout = dict(title={'text':'Alumni Salary across Schools', 'x':0.5},
86 | barmode='group', xaxis=dict(tickmode='linear'))
87 | ```
88 |
89 |
90 | ## Reference
91 | Plotly Documentation Box Plot
--------------------------------------------------------------------------------
/PlotlyExample/BoxPlot/box.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/BoxPlot/box.png
--------------------------------------------------------------------------------
/PlotlyExample/BoxPlot/boxplot_simple.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Prepare data
13 | data = []
14 | for school in df['school'].unique():
15 | df_temp = df[df['school']==school]
16 | data.append(go.Box(y=df_temp['salary'], name=school, boxmean=True))
17 |
18 | # Layout
19 | layout = dict(title={'text':'Alumni Salary across Schools', 'x':0.5},
20 | barmode='group', xaxis=dict(tickmode='linear'))
21 |
22 | fig = go.Figure(data=data, layout=layout)
23 |
24 | plotly.offline.plot(fig, filename='box.html')
--------------------------------------------------------------------------------
/PlotlyExample/CandlestickChart/AAPLprice.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import yfinance
3 | import plotly
4 | import plotly.graph_objs as go
5 | from plotly.offline import *
6 |
7 |
8 | # To initiate ploty to run offline
9 | init_notebook_mode(connected=True)
10 |
11 | apple = yfinance.Ticker('AAPL')
12 | df = apple.history(period='ytd').reset_index()
13 |
14 | data = []
15 | data.append(go.Candlestick(x=df['Date'], open=df['Open'],
16 | high=df['High'], low=df['Low'],
17 | close=df['Close']))
18 | layout = {'title':{'text':'Year-to-Date Apple Stock Price','x':0.5},
19 | 'xaxis':{'title':'Date','rangeslider':{'visible':False}},
20 | 'yaxis':{'title':'Price ($)'},
21 | 'hovermode':False}
22 | fig = go.Figure(data=data, layout=layout)
23 |
24 | plotly.offline.plot(fig, filename='apple_candlestick.html')
25 |
--------------------------------------------------------------------------------
/PlotlyExample/CandlestickChart/Candlestick.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/CandlestickChart/Candlestick.png
--------------------------------------------------------------------------------
/PlotlyExample/CandlestickChart/Readme.md:
--------------------------------------------------------------------------------
1 | # Candlestick Charts
2 | Candlestick chart is chart to display the price, including opening price, closing price, highest and lowest price, of a security or derivatives in a given period. In this folder, we will go over how to create candlestick charts with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
9 |
10 | ## Pacakges Needed
11 | This chapter requires the following packages for the scripts used:
12 |
13 | - Pandas
14 | - Plotly
15 | - yfinance (Only used for AAPLprice.py to obtain data, does not require if you have any data set from other sources)
16 |
17 |
18 | ## Data Used
19 | This chapter may obtain Apple stock price via API call using yfinance. In this
20 |
21 | ## Syntax
22 | ### Data
23 | Data is a list of go.Candlestick(). Although you are expected to only have one go.Candlestick() in the list, you should put go.Candlestick() in a list for Plotly.
24 |
25 | go.Candlestick() has the following parameters:
26 |
27 | - x: Date
28 | - open: Opening price of the security/derivative
29 | - high: Highest price of the security/derivative
30 | - low: Lowest price of the security/derivative
31 | - close: Closing price of the security/derivative
32 |
33 |
34 |
35 |
36 | ### Layout
37 | Genetic Layout parameters suggested to use:
38 |
39 | - title (Dictionary): Chart title and fonts
40 |
41 | - text: Chart title to be displayed
42 | - x: text location on x-dimension, from 0-1
43 | - y: text location on y-dimension, from 0-1
44 |
45 | - yaxis (Dictionary): Y-axis setting
46 |
47 | - title: Y-axis title
48 | - tickmode: Setting of ticks
49 |
50 |
51 | - xaxis (Dictionary): X-axis setting
52 |
53 | - title: X-axis title
54 | - tickmode: Setting of ticks
55 |
56 | - rangeslider (Dicionary): Whether to include rangeslider for user to shrink or expand the range, default to True
and display the same candlestick chart in the rangeslider
57 |
58 |
59 |
60 |
61 |
62 | Candlestick Chart Exclusive parameters:
63 |
64 | - Data
65 |
66 | - open: Opening price of the security/derivative
67 | - high: Highest price of the security/derivative
68 | - low: Lowest price of the security/derivative
69 | - close: Closing price of the security/derivative
70 |
71 | - Layout
72 |
73 | - xaxis (Dictionary): y-axis setting
74 |
75 | - rangeslider (Dicionary): Whether to include rangeslider for user to shrink or expand the range
76 |
77 |
78 |
79 |
80 |
81 |
82 | ## Examples
83 | ### Simple Candlestick Chart
84 |
85 |
86 | ```
87 | # Prepare data
88 | data.append(go.Candlestick(x=df['Date'], open=df['Open'],
89 | high=df['High'], low=df['Low'],
90 | close=df['Close']))
91 |
92 | layout = {'title':{'text':'Year-to-Date Apple Stock Price','x':0.5},
93 | 'xaxis':{'title':'Date','rangeslider':{'visible':False}},
94 | 'yaxis':{'title':'Price ($)'},
95 | 'hovermode':False}
96 | ```
97 |
98 | By default, Plotly set rangeslider to be visible. You must turn off manually.
99 |
100 | ## Reference
101 | Plotly Documentation Candlestick Chart
102 |
--------------------------------------------------------------------------------
/PlotlyExample/ChoroplethGraph/Example_Basic_ChoroplethGraph.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.figure_factory as ff
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | df_rent = pd.read_csv('../Data/county_avg_rent.csv')
11 | df_fips = pd.read_csv('../Data/countyfips.csv')
12 |
13 | df = df_rent.merge(df_fips, on='countyname', how='inner')
14 | df = df[(df['fips'] >= 6000) & (df['fips'] <= 7000)]
15 |
16 | # Define the endpoints
17 | endpts = list(range(1,6))
18 |
19 | fig = ff.create_choropleth(
20 | fips = df['fips'], values = df['median_sqft_price'],
21 | colorscale = plotly.colors.sequential.Oranges,
22 | show_state_data = True, scope = ['CA'],
23 | binning_endpoints=endpts,
24 | county_outline={'color': 'rgb(15,15,55)', 'width': 1},
25 | state_outline={'color': 'rgb(15,15,55)', 'width': 1},
26 | legend_title='Median Rent')
27 |
28 | fig.update_layout(title={'text':'Median Rent per Square Foot by County', 'x':0.5})
29 |
30 | plotly.offline.plot(fig, filename='basic_choropleth.html')
31 |
--------------------------------------------------------------------------------
/PlotlyExample/ChoroplethGraph/Readme.md:
--------------------------------------------------------------------------------
1 | # Choropleth Graphs
2 | Choropleth graphs are maps with coloured areas to display the values to each geo location. Plotly's Choropleth Graph supports various maps, including the world and the US. In this folder, we will go over how to create chropleth graphs with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
7 | - Example_Basic_ChoroplethGraph.py
8 |
9 |
10 | ## Pacakges Needed
11 | This chapter requires the following packages for the scripts used:
12 |
13 | - Pandas
14 | - Plotly
15 |
16 |
17 | ## Data Used
18 | This chapter may use the following data from the [Data folder](../Data):
19 |
20 | - county_avg_rent.csv
21 | - countyfips.csv
22 |
23 |
24 | ### countyfips.csv
25 | Plotly has a feature to draw borders based on FIPS (Federal Information Processing Standards) defined by the US government, so Plotly could draw the border automatically if you have connected the data with FIPS. countyfips.csv is the table for all FIPS number for all counties in the US.
26 |
27 | ## Syntax
28 | ### Approach 1 - figure_factory.create_choropleth()
29 | figure_factory.create_choropleth() is a easy way to create choropleth graphs in the United States, especially only displaying individual state. Different with the go.Figure(), figure_factory.create_choropleth() takes all data parameters and layout parameters.
30 |
31 | figure_factory.create_choropleth() has the following parameters:
32 |
33 | - fips: FIPS (Federal Information Processing Standards) defined by the US government, an attribute to locate the counties in United States
34 | - values: Values
35 | - colorscale: The set of colours to display the value of each area, see plotly.colors.sequential for colour sets
36 | - show_state_data: (Coming Soon...)
37 | - scope: The map used in the visualization
38 | - binning_endpoints: To map the range of values to colorscale
39 | - county_outline (Dictionary): Define the lines on county borders
40 |
41 | - color: Color of county borders, RGB or Hex in string
42 | - width: The width of borderline in px, integer
43 |
44 | - state_outline (Dictionary): Define the lines on state borders
45 | - color: Color of county borders, RGB or Hex in string
46 | - width: The width of borderline in px, integer
47 |
48 |
49 |
50 |
51 |
52 | Choropleth Graph Exclusive parameters:
53 |
54 | - fips: FIPS (Federal Information Processing Standards) defined by the US government, an attribute to locate the counties in United States
55 | - show_state_data: (Coming Soon...)
56 | - scope: The map used in the visualization
57 | - binning_endpoints: To map the range of values to colorscale
58 | - county_outline (Dictionary): Define the lines on county borders
59 |
60 | - color: Color of county borders, RGB or Hex in string
61 | - width: The width of borderline in px, integer
62 |
63 | - state_outline (Dictionary): Define the lines on state borders
64 | - color: Color of county borders, RGB or Hex in string
65 | - width: The width of borderline in px, integer
66 |
67 |
68 |
69 | ## Examples
70 | ### Example 1 - Using figure_factory.create_choropleth()
71 |
72 |
73 | ```
74 | # Define the endpoints
75 | endpts = list(range(1,6))
76 |
77 | fig = ff.create_choropleth(
78 | fips = df['fips'], values = df['median_sqft_price'],
79 | colorscale = plotly.colors.sequential.Oranges,
80 | show_state_data = True, scope = ['CA'],
81 | binning_endpoints=endpts,
82 | county_outline={'color': 'rgb(15,15,55)', 'width': 1},
83 | state_outline={'color': 'rgb(15,15,55)', 'width': 1},
84 | legend_title='Median Rent')
85 |
86 | ```
87 |
88 |
89 | ## Reference
90 | Plotly Documentation Choropleth Graph
--------------------------------------------------------------------------------
/PlotlyExample/ChoroplethGraph/basic_choropleth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ChoroplethGraph/basic_choropleth.png
--------------------------------------------------------------------------------
/PlotlyExample/Data/county_avg_rent.csv:
--------------------------------------------------------------------------------
1 | countyname,median_sqft_price
2 | San Francisco County,4.666666666666667
3 | San Mateo County,3.7575528700906347
4 | Marin County,3.3090185676392574
5 | Santa Clara County,3.2785714285714285
6 | Alameda County,3.042125883285922
7 | Ventura County,2.6263520157325466
8 | Los Angeles County,2.6
9 | Contra Costa County,2.4832428552200634
10 | San Bernardino County,2.384370015948963
11 | Sonoma County,2.3125
12 | Napa County,2.3005514705882355
13 | San Diego County,2.2846153846153845
14 | Orange County,2.22
15 | Solano County,2.2043628013777266
16 | Sutter County,2.125
17 | Monterey County,2.0
18 | Kern County,1.9134615384615385
19 | San Joaquin County,1.8502994011976048
20 | El Dorado County,1.751927119831815
21 | Placer County,1.7085470085470085
22 | Yolo County,1.6833333333333333
23 | Riverside County,1.6709710743801653
24 | Sacramento County,1.6584766584766584
25 | Mendocino County,1.6159695817490494
26 | Lake County,1.25
27 | San Luis Obispo County,1.0344827586206897
28 |
--------------------------------------------------------------------------------
/PlotlyExample/Data/cust_num.csv:
--------------------------------------------------------------------------------
1 | day,hour,customers_count
2 | Monday,11,200
3 | Monday,12,600
4 | Monday,13,800
5 | Monday,14,400
6 | Monday,15,300
7 | Monday,16,250
8 | Monday,17,150
9 | Monday,18,350
10 | Monday,19,450
11 | Monday,20,120
12 | Tuesday,11,250
13 | Tuesday,12,750
14 | Tuesday,13,1050
15 | Tuesday,14,700
16 | Tuesday,15,400
17 | Tuesday,16,150
18 | Tuesday,17,350
19 | Tuesday,18,650
20 | Tuesday,19,250
21 | Tuesday,20,180
22 | Wednesday,11,160
23 | Wednesday,12,820
24 | Wednesday,13,1400
25 | Wednesday,14,490
26 | Wednesday,15,170
27 | Wednesday,16,210
28 | Wednesday,17,420
29 | Wednesday,18,510
30 | Wednesday,19,910
31 | Wednesday,20,400
32 | Thursday,11,90
33 | Thursday,12,300
34 | Thursday,13,450
35 | Thursday,14,320
36 | Thursday,15,70
37 | Thursday,16,230
38 | Thursday,17,140
39 | Thursday,18,500
40 | Thursday,19,370
41 | Thursday,20,220
42 | Friday,11,400
43 | Friday,12,1800
44 | Friday,13,2240
45 | Friday,14,1480
46 | Friday,15,840
47 | Friday,16,1320
48 | Friday,17,1570
49 | Friday,18,2160
50 | Friday,19,1820
51 | Friday,20,740
52 | Saturday,11,600
53 | Saturday,12,1720
54 | Saturday,13,2340
55 | Saturday,14,2410
56 | Saturday,15,1950
57 | Saturday,16,1620
58 | Saturday,17,1840
59 | Saturday,18,1970
60 | Saturday,19,1340
61 | Saturday,20,1210
62 | Sunday,11,300
63 | Sunday,12,1240
64 | Sunday,13,1120
65 | Sunday,14,1400
66 | Sunday,15,1380
67 | Sunday,16,1650
68 | Sunday,17,1390
69 | Sunday,18,1150
70 | Sunday,19,950
71 | Sunday,20,720
--------------------------------------------------------------------------------
/PlotlyExample/Data/ecom_funnel.csv:
--------------------------------------------------------------------------------
1 | "shop","stage","count"
2 | "Shop A","Landing Page","45000"
3 | "Shop A","Add Item to Cart","76000"
4 | "Shop A","Go to Cart","21000"
5 | "Shop A","Check Out","20000"
6 | "Shop A","Complete Transaction","19000"
7 | "Shop B","Landing Page","25000"
8 | "Shop B","Add Item to Cart","36000"
9 | "Shop B","Go to Cart","9000"
10 | "Shop B","Check Out","8000"
11 | "Shop B","Complete Transaction","7500"
--------------------------------------------------------------------------------
/PlotlyExample/Data/expense_dept.csv:
--------------------------------------------------------------------------------
1 | category,expense
2 | Salary,800000
3 | Rent,200000
4 | Overheads,250000
--------------------------------------------------------------------------------
/PlotlyExample/Data/expense_everybody.csv:
--------------------------------------------------------------------------------
1 | name,expense_category,amount
2 | Acca,food,40.23
3 | Acca,transportation,60.23
4 | Acca,food,20.34
5 | Acca,food,60.94
6 | Acca,food,12.47
7 | Fred,transportation,32.56
8 | Fred,transportation,20.76
9 | Fred,food,13.29
10 | Fred,transportation,17.43
11 | Wilson,food,9.6
12 | Wilson,transportation,62.53
13 | Wilson,food,13.24
14 | Wilson,food,21.54
15 | Wilson,transportation,32.62
16 | Wilson,food,70.23
17 | Wilson,transportation,42.53
18 | Andrew,food,60.44
19 | Andrew,food,80.28
20 | Andrew,food,24.72
21 | Andrew,food,52.30
22 | Jacques,food,30.23
23 | Jacques,food,84.56
24 | Jacques,food,8.34
25 | Jacques,transportation,56.78
26 | Tim,food,82.62
27 | Tim,food,68.34
28 | Tim,food,92.49
29 | Tim,food,104.53
30 | Tim,food,75.24
31 | Tim,transportation,62.89
32 |
--------------------------------------------------------------------------------
/PlotlyExample/Data/grades.csv:
--------------------------------------------------------------------------------
1 | student_id,name,math_grade,eng_grade,sci_grade,his_grade,semester
2 | 1,Jacques,92,82,88,98,1
3 | 2,Rodney,72,80,82,100,1
4 | 3,Jeremy,74,92,84,96,1
5 | 4,Henry,98,92,94,82,1
6 | 5,Sunny,100,90,94,80,1
7 | 1,Jacques,94,88,82,100,2
8 | 2,Rodney,70,83,85,97,2
9 | 3,Jeremy,81,88,78,99,2
10 | 4,Henry,92,100,100,78,2
11 | 5,Sunny,99,93,99,82,2
12 | 1,Jacques,100,78,80,100,3
13 | 2,Rodney,81,82,87,100,3
14 | 3,Jeremy,88,92,79,96,3
15 | 4,Henry,95,99,100,82,3
16 | 5,Sunny,98,94,88,82,3
17 |
--------------------------------------------------------------------------------
/PlotlyExample/Data/hk_population.csv:
--------------------------------------------------------------------------------
1 | area,district,population
2 | Island,Central,55000
3 | Island,Causeway Bay,70000
4 | Island,North Point,125000
5 | Island,Kennedy Town,80000
6 | Kowloon,Kowloon City,130000
7 | Kowloon,Mong Kok,90000
8 | Kowloon,Kowloon Bay,150000
9 | Kowloon,Ho Man Tin,115000
10 | Kowloon,Kwun Tong,185000
11 | Kowloon,Sham Shui Po,280000
12 | New Territories,Sha Tin,550000
13 | New Territories,Tai Po,400000
14 | New Territories,Yuen Long,350000
--------------------------------------------------------------------------------
/PlotlyExample/Data/revenue_dept.csv:
--------------------------------------------------------------------------------
1 | category,revenue
2 | Clothing,450000
3 | Electronics,1250000
4 | Grocery,230000
5 | Toys,370000
--------------------------------------------------------------------------------
/PlotlyExample/Data/salary.csv:
--------------------------------------------------------------------------------
1 | name,school,major,salary
2 | Acca,UC Davis,Economics,120000
3 | Wilson,UC Davis,Data Science,90000
4 | Tim,UC Davis,Economics,90000
5 | Andrew,UC Davis,Data Science,100000
6 | Grace,UC Davis,Biology,80000
7 | Carmen,UC Davis,Biology,90000
8 | Jacques,UC Davis,Data Science,250000
9 | Edward,San Jose State,Data Science,50000
10 | Jeffrey,San Jose State,Data Science,20000
11 | Cherry,San Jose State,Data Science,40000
12 | Mary,San Jose State,Economics,65000
13 | Danny,San Jose State, Economics,48000
--------------------------------------------------------------------------------
/PlotlyExample/Data/tips.csv:
--------------------------------------------------------------------------------
1 | name,meal_type,grand_total,tips,wait_mins
2 | Acca,Dinner,40.23,6.5,10
3 | Acca,Lunch,20.34,4,23
4 | Acca,Dinner,60.94,10.06,10
5 | Acca,Coffee,12.47,2.53,5
6 | Fred,Lunch,13.29,1.71,30
7 | Wilson,Coffee,9.6,1.4,3
8 | Wilson,Lunch,13.24,2.76,5
9 | Wilson,Dinner,21.54,4,12
10 | Wilson,Dinner,70.23,12.5,9
11 | Jacques,Dinner,30.23,5.77,8
12 | Jacques,Dinner,84.56,14.44,15
13 | Jacques,Coffee,8.34,1.25,8
14 | Tim,Dinner,82.62,14.5,14
15 | Tim,Lunch,68.34,12.8,19
16 | Tim,Lunch,92.49,10.51,32
17 | Tim,Dinner,104.53,18.7,16
18 | Tim,Lunch,75.24,9.26,22
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/readme.md:
--------------------------------------------------------------------------------
1 | # Funnel Chart
2 | Funnel charts are useful for conversion events or cohort analysis, such as sales cycles.
3 |
4 |
5 | ## Files
6 | The following scripts are used in this chapter:
7 |
8 | - simple_funnel.py
9 | - stack_funnel.py
10 | - simple_funnelarea.py
11 |
12 |
13 | ## Pacakges Needed
14 | This chapter requires the following packages for the scripts used:
15 |
16 | - Pandas
17 | - Plotly
18 |
19 |
20 | ## Data Used
21 | This chapter may use the following data from the [Data folder](../Data):
22 |
23 | - ecom_funnel.csv
24 |
25 |
26 | ## Syntax
27 | ### Data
28 | Data is a list to store either go.Funnel() or go.Funnelarea(). The difference... Please note that x accepts facts or numerics values, while y accepts attribute values or categorical values. Swapping x and y will lead to unexpected behaviour!
29 |
30 | #### go.Funnel()
31 | go.Funnel() has the following parameters:
32 |
33 | - x: The numeric value of the attribute
34 | - y: A categorical value
35 | - name: Category, which will be used for identifying the stacked funnel
36 | - marker: Setting for the funnel bar
37 |
38 | - color: The colour of the area of each attribute
39 | - line: The setting for the line
40 |
41 | - width
42 | - line
43 |
44 | - connector: The setting for the connector between each funnel bar
45 |
46 | - line
47 |
48 | - color
49 | - dash
50 |
51 |
52 |
53 |
54 | - textposition: Text position for y, it can be:
55 |
56 | - inside
57 | - outside
58 | - auto
59 | - none
60 |
61 |
62 | - textinfo: Determines which trace information appear on the graph, it can be:
63 |
64 | - text
65 | - value
66 | - current path
67 | - percent root
68 | - percent entry
69 | - percent parent
70 | - Or any combination of them, simply put a + sign between the values above without white space in between
71 |
72 |
73 | - hoverinfo: What information to be displayed when user hover over the coloured area, all the options are:
74 |
75 | - percent
76 | - label+percent
77 | - label
78 | - name
79 |
80 |
81 |
82 |
83 | #### go.Funnelarea()
84 | Note: go.Funnelarea() uses value and text! Instead of x and y
85 |
86 | go.Funnelarea() has the following parameters:
87 |
88 | - value: The numeric value of the attribute
89 | - text: A categorical value (Shown on funnel bars)
90 | - labels: Categorical values (Shown on legend)
91 | - marker: Setting for the funnel bar
92 |
93 | - color: The colour of the area of each attribute
94 | - pattern: Setting on how to fill the funnel bars, such as full filled or striped filled
95 | - line: The setting for the line
96 |
97 | - width
98 | - line
99 |
100 | - connector: The setting for the connector between each funnel bar
101 |
102 | - line
103 |
104 | - color
105 | - dash
106 |
107 |
108 |
109 |
110 | - textposition: Text position for y, it can be:
111 |
112 | - inside
113 | - outside
114 | - auto
115 | - none
116 |
117 |
118 | - textinfo: Determines which trace information appear on the graph, it can be:
119 |
120 | - text
121 | - value
122 | - current path
123 | - percent root
124 | - percent entry
125 | - percent parent
126 | - Or any combination of them, simply put a + sign between the values above without white space in between
127 |
128 |
129 | - hoverinfo: What information to be displayed when user hover over the coloured area, all the options are:
130 |
131 | - percent
132 | - label+percent
133 | - label
134 | - name
135 |
136 |
137 |
138 |
139 | ## Example 1 - Simple Funnel Chart
140 |
141 |
142 | ```
143 | fig = go.Figure(go.Funnel(
144 | y = df['stage'],
145 | x = df['count'])
146 | )
147 | ```
148 |
149 | ## Example 2 - Stacked Funnel Chart
150 |
151 |
152 | ```
153 | data = []
154 | for shop in df['shop'].unique():
155 | df_temp = df[df['shop']==shop]
156 | data.append(go.Funnel(
157 | name = shop,
158 | y = df_temp['stage'],
159 | x = df_temp['count'])
160 | )
161 | ```
162 |
163 | ## Example 3 - Simple Funnel Area
164 |
165 |
166 |
167 | Use text if you want attribute and values on funnel bars.
168 |
169 | ```
170 | fig = go.Figure(go.Funnelarea(
171 | text = df['stage'], # Text displayed on funnel bars
172 | values = df['count'])
173 | )
174 | ```
175 |
176 |
177 |
178 |
179 | Use labels if you do not want attribute on funnel bars, but on legned. The values will still stated on funnel bars unless you turn it off.
180 |
181 | ```
182 | fig = go.Figure(go.Funnelarea(
183 | labels = df['stage'], # Text displayed only in legend
184 | values = df['count'])
185 | )
186 | ```
187 |
188 | ## Reference
189 | Plotly Documentation Funnel Charts
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/simple_funnel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/FunnelChart/simple_funnel.png
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/simple_funnel.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/ecom_funnel.csv')
12 | df = df[df['shop']=='Shop A']
13 |
14 | fig = go.Figure(go.Funnel(
15 | y = df['stage'],
16 | x = df['count'])
17 | )
18 |
19 | plotly.offline.plot(fig, filename='simple_funnel.html')
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/simple_funnelarea.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/ecom_funnel.csv')
12 | df = df[df['shop']=='Shop A']
13 |
14 | fig = go.Figure(go.Funnelarea(
15 | text = df['stage'], # Text displayed on funnel bars
16 | # labels = df['stage'], # Text displayed only in legend
17 | values = df['count'])
18 | )
19 |
20 | plotly.offline.plot(fig, filename='simple_funnelarea.html')
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/simple_funnelarea1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/FunnelChart/simple_funnelarea1.png
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/simple_funnelarea2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/FunnelChart/simple_funnelarea2.png
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/stack_funnel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/FunnelChart/stack_funnel.png
--------------------------------------------------------------------------------
/PlotlyExample/FunnelChart/stack_funnel.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/ecom_funnel.csv')
12 |
13 | data = []
14 | for shop in df['shop'].unique():
15 | df_temp = df[df['shop']==shop]
16 | data.append(go.Funnel(
17 | name = shop,
18 | y = df_temp['stage'],
19 | x = df_temp['count'])
20 | )
21 | # Layout
22 | layout = dict(title={'text':'Ecommerce Funnel', 'x':0.5},
23 | barmode='group', xaxis=dict(tickmode='linear'))
24 |
25 | fig = go.Figure(data=data, layout=layout)
26 |
27 | plotly.offline.plot(fig, filename='stack_funnel.html')
--------------------------------------------------------------------------------
/PlotlyExample/Heatmap/Readme.md:
--------------------------------------------------------------------------------
1 | # Heatmaps
2 | Heatmap. In this folder, we will go over how to create bar charts with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
7 | - Simple_heatmap.py
8 |
9 |
10 | ## Pacakges Needed
11 | This chapter requires the following packages for the scripts used:
12 |
13 | - Pandas
14 | - Plotly
15 |
16 |
17 | ## Data Used
18 | This chapter may use the following data from the [Data folder](../Data):
19 |
22 |
23 | ### cust_num.csv
24 | cust_num.csv is data set that records the customer traffic of a hypothetical department store by day of week and hours.
25 |
26 | ## Syntax
27 | ### Data
28 | Data is a list to store go.Heatmap().
29 |
30 | go.heatmap() has the following parameters:
31 |
32 | - x: Attribute on x-axis
33 | - y: Attribute on y-axis
34 | - z: Value of the attribute on x and y-axis, and display in colour
35 | - colorscale: The colour scale on how data is displayed, depends on z
36 | - hoverongaps: When there is missing value in the data, it will not show hovertext if this column is set to false (Default to true)
37 | - hoverinfo: What information to be displayed when user hover over the coloured area, all the options are:
38 |
39 | - percent
40 | - label+percent
41 | - label
42 | - name
43 |
44 |
45 |
46 |
47 |
48 | ### Layout
49 | Genetic Layout parameters suggested to use:
50 |
51 | - title (Dictionary): Chart title and fonts
52 |
53 | - text: Chart title to be displayed
54 | - x: text location on x-dimension, from 0-1
55 | - y: text location on y-dimension, from 0-1
56 |
57 | - xaxis (Dictionary): X-axis setting
58 |
59 | - tickmode: Setting of ticks
60 | - tickangle: Degree the tick rotate (-: Anticlockwise, +: Clockwise)
61 |
62 | - yaxis (Dictionary): y-axis setting
63 |
64 | - tickmode: Setting of ticks
65 | - tickangle: Degree the tick rotate (-: Anticlockwise, +: Clockwise)
66 |
67 |
68 |
69 |
70 | Heatmap Exclusive parameters:
71 |
72 | - z: Value of the attribute on x and y-axis
73 | - hoverongaps: Display or not if data is missing
74 |
75 |
76 | ## Examples
77 | ### Example 1 - Simple Heatmap
78 |
79 |
80 | ```
81 | # Data
82 | data = []
83 | data.append(go.Heatmap(z=df['customers_count'],
84 | x=df['day'], y=df['hour'],
85 | colorscale='ylorrd'))
86 |
87 | # Layout
88 | layout = {'title':{'text':'Department Store Traffic',
89 | 'x':0.5},
90 | 'xaxis': {'tickmode':'linear'},
91 | 'yaxis': {'tickmode':'linear'}}
92 |
93 | ```
94 |
95 | Note: For some reason, z-axis must be declared before x-axis and y-axis in go.Heatmap()!
96 |
97 | ## Reference
98 | Plotly Documentation Heatmaps
--------------------------------------------------------------------------------
/PlotlyExample/Heatmap/Simple_heatmap.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/cust_num.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Heatmap(z=df['customers_count'],
15 | x=df['day'], y=df['hour'],
16 | colorscale='ylorrd'))
17 |
18 | # Layout
19 | layout = {'title':{'text':'Department Store Traffic',
20 | 'x':0.5},
21 | 'xaxis': {'tickmode':'linear'},
22 | 'yaxis': {'tickmode':'linear'}}
23 |
24 | fig = go.Figure(data=data, layout=layout)
25 |
26 | plotly.offline.plot(fig, filename='simple_heatmap.html')
--------------------------------------------------------------------------------
/PlotlyExample/Heatmap/simpleheatmap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Heatmap/simpleheatmap.png
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/AggregatedHistogram.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Histogram(x=df['salary'], y=df['salary'], histfunc='sum'))
15 | # Layout
16 | layout = {'title':{'text':'Everybody\'s Salary (Summation by Group)', 'x':0.5}}
17 |
18 | fig = go.Figure(data=data, layout=layout)
19 |
20 | plotly.offline.plot(fig, filename='aggregated_histogram.html')
21 |
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/CumulativeHistogram.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Histogram(x=df['salary'], cumulative_enabled=True,
15 | xbins={'size':25000}))
16 | # Layout
17 | layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5}}
18 |
19 | fig = go.Figure(data=data, layout=layout)
20 |
21 | plotly.offline.plot(fig, filename='cumulative_histogram.html')
22 |
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/NormalizedHistogram.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import plotly
4 | import plotly.graph_objs as go
5 | from plotly.offline import *
6 |
7 |
8 | # To initiate ploty to run offline
9 | init_notebook_mode(connected=True)
10 | # Import data
11 | df = pd.read_csv('../Data/salary.csv')
12 |
13 | # Data
14 | data = []
15 | x = np.random.randn(500)
16 | data.append(go.Histogram(x=x, histnorm='probability'))
17 | # Layout
18 | layout = {'title':{'text':'Distribution of 500 Random Numbers', 'x':0.5}}
19 |
20 | fig = go.Figure(data=data, layout=layout)
21 |
22 | plotly.offline.plot(fig, filename='normalized_histogram.html')
23 |
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/OverlaidHistogram.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Data
13 | data = []
14 | for group in df['school'].unique():
15 | df_temp = df[df['school']==group]
16 | data.append(go.Histogram(x=df_temp['salary'],name=group,
17 | xbins={'size':50000}))
18 | # Layout
19 | layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5},
20 | 'barmode':'overlay'}
21 |
22 | fig = go.Figure(data=data, layout=layout)
23 |
24 | plotly.offline.plot(fig, filename='overlaid_histogram.html')
25 |
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/SimpleHistogram.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Histogram(x=df['salary']))
15 | # Layout
16 | layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5}}
17 |
18 | fig = go.Figure(data=data, layout=layout)
19 |
20 | plotly.offline.plot(fig, filename='simple_histogram.html')
21 |
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/StackedHistogram.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/salary.csv')
11 |
12 | # Data
13 | data = []
14 | for group in df['school'].unique():
15 | df_temp = df[df['school']==group]
16 | data.append(go.Histogram(x=df_temp['salary'],name=group,
17 | xbins={'size':50000}))
18 | # Layout
19 | layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5},
20 | 'barmode':'stack'}
21 |
22 | fig = go.Figure(data=data, layout=layout)
23 |
24 | plotly.offline.plot(fig, filename='stacked_histogram.html')
25 |
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/aggregated_histogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Histogram/aggregated_histogram.png
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/cumulative_histogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Histogram/cumulative_histogram.png
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/normalized_histogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Histogram/normalized_histogram.png
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/overlaid_histogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Histogram/overlaid_histogram.png
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/simple_histogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Histogram/simple_histogram.png
--------------------------------------------------------------------------------
/PlotlyExample/Histogram/stacked_histogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Histogram/stacked_histogram.png
--------------------------------------------------------------------------------
/PlotlyExample/LineChart/Mutlilines_Linechart.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/cust_num.csv')
11 |
12 | colour_scheme = ['red','blue','black','orange','yellow','brown','green']
13 |
14 | # Data
15 | data = []
16 | for day, colour in zip(df['day'].unique(), colour_scheme):
17 | df_temp = df[df['day']==day]
18 | data.append(go.Scatter(x=df_temp['hour'], y=df_temp['customers_count'],
19 | line={'color': colour},
20 | name=day,
21 | mode='lines'))
22 | # Layout
23 | layout = {'title':{'text':'Number of Customer Trend by Days', 'x':0.5}}
24 |
25 | fig = go.Figure(data=data, layout=layout)
26 |
27 | plotly.offline.plot(fig, filename='mutlilines_linechart.html')
--------------------------------------------------------------------------------
/PlotlyExample/LineChart/SimpleLinechart.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/cust_num.csv')
11 |
12 | df = df[df['day']=='Monday']
13 |
14 | # Data
15 | data = []
16 | data.append(go.Scatter(x=df['hour'], y=df['customers_count'],
17 | mode='lines'))
18 | # Layout
19 | layout = {'title':{'text':'Number of Customer Trend', 'x':0.5}}
20 |
21 | fig = go.Figure(data=data, layout=layout)
22 |
23 | plotly.offline.plot(fig, filename='simple_linechart.html')
--------------------------------------------------------------------------------
/PlotlyExample/LineChart/SimpleLinechart_points.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/cust_num.csv')
11 |
12 | df = df[df['day']=='Monday']
13 |
14 | # Data
15 | data = []
16 | data.append(go.Scatter(x=df['hour'], y=df['customers_count'],
17 | mode='lines+markers'))
18 | # Layout
19 | layout = {'title':{'text':'Number of Customer Trend', 'x':0.5}}
20 |
21 | fig = go.Figure(data=data, layout=layout)
22 |
23 | plotly.offline.plot(fig, filename='simple_linechart_points.html')
--------------------------------------------------------------------------------
/PlotlyExample/LineChart/multilines.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/LineChart/multilines.png
--------------------------------------------------------------------------------
/PlotlyExample/LineChart/readme.md:
--------------------------------------------------------------------------------
1 | # Line Chart
2 | Line chart is a visualization that uses lines to connect a series of data points to show the trend of categories of data. Line Chart, Bubble Chart and Scatter Plot in Plotly use the same module to plot the visualization. In this folder, we are going to go over how to create line charts with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
7 | - SimpleLinechart.py
8 | - SimpleLinechart_points.py
9 | - Mutlilines_Linechart.py
10 |
11 |
12 | ## Pacakges Needed
13 | This chapter requires the following packages for the scripts used:
14 |
15 | - Pandas
16 | - Plotly
17 |
18 |
19 | ## Data Used
20 | This chapter may use the following data from the [Data folder](../Data):
21 |
24 |
25 | ## Syntax
26 | ### Data
27 | Data is a list of go.Scatter(), each go.Scatter() represents a category of points and/or a line.
28 |
29 | If the data list could have 1 or mutliple go.Scatter(), to represent a line, or mutliple lines. If it is a collection of points, refer to the [ScatterPlot folder](../ScatterPlot).
30 |
31 | go.Scatter() has the following parameters:
32 |
33 | - x: Attribute on x-axis
34 | - y: Value on y-axis
35 | - line: In depth setting for data point, including
36 |
37 | - color: Set color for the line, accept RGB values/Colour keywords
38 |
39 |
40 | - mode: Setting on how to display
41 |
42 | - markers: Display data points only
43 | - lines: Display in lines only
44 | - lines+maker: Dispaly in lines with data points
45 |
46 |
47 | - name: Explanation shown in legend
48 | - text: The text label will displayed on the lines
49 | - textfont (Dictionary): Text label setting
50 | - hoverinfo: What information to be displayed when user hover over the bar, all the options are:
51 |
52 | - percent
53 | - label+percent
54 | - text
55 | - name
56 |
57 |
58 |
59 |
60 |
61 |
62 | ### Layout
63 | Genetic Layout parameters suggested to use:
64 |
65 | - title (Dictionary): Chart title and fonts
66 |
67 | - text: Chart title to be displayed
68 | - x: text location on x-dimension, from 0-1
69 | - y: text location on y-dimension, from 0-1
70 |
71 | - xaxis (Dictionary): X-axis setting
72 |
73 | - tickmode: Setting of ticks
74 | - tickangle: Degree the tick rotate (-: Anticlockwise, +: Clockwise)
75 | - categoryorder: Sort the order of attributes on X-axis, either ascending or descending
76 |
77 | - category ascending: Sort attribute (attribute in name in Data) in ascending orders
78 | - category descending: Sort attribute (attribute in name in Data) in descending orders
79 | - total ascending: Sort value in ascending orders
80 | - total descending: Sort value in descending orders
81 | - min ascending/min descending: Sort by minimum value
82 | - max ascending/max descending: Sort by maximum value
83 | - sum ascending/sum descending: Sort by summation value
84 | - mean ascending/mean descending: Sort by average value
85 | - median ascending/median descending: Sort by median value
86 | - array: Follow the sorting order defined in categoryarray
87 |
88 |
89 | - dtick: The frequency the labels appear, the default setting is determined automatically
90 | - categoryarray: Define the sorting order when categoryorder is array
91 | - type: Set axis scale, default is linear (linear, log, date, category, multicategory)
92 |
93 | - yaxis (Dictionary): y-axis setting
94 |
95 | - tickmode: Setting of ticks
96 | - tickangle: Degree the tick rotate (-: Anticlockwise, +: Clockwise)
97 | - dtick: The frequency the labels appear, the default setting is determined automatically
98 | - type: Set axis scale, default is linear (linear, log, date, category, multicategory)
99 |
100 |
101 |
102 |
103 |
104 | Line Chart Exclusive parameters:
105 | Scatter Plot Exclusive parameters:
106 |
107 | - marker_color
108 | - marker
109 |
110 |
111 | ## Examples
112 | ### Example 1 - Simple Line Chart
113 |
114 |
115 | ```
116 | # Data
117 | data = []
118 | data.append(go.Scatter(x=df['hour'], y=df['customers_count'],
119 | mode='lines'))
120 | # Layout
121 | layout = {'title':{'text':'Number of Customer Trend', 'x':0.5}}
122 |
123 | fig = go.Figure(data=data, layout=layout)
124 | ```
125 |
126 | Note: Simply use go.Scatter() and set mode to lines
127 |
128 | ### Example 2 - Simple Line Chart with Data Points
129 |
130 |
131 |
132 | ```
133 | # Data
134 | data = []
135 | data.append(go.Scatter(x=df['hour'], y=df['customers_count'],
136 | mode='lines+markers'))
137 | # Layout
138 | layout = {'title':{'text':'Number of Customer Trend', 'x':0.5}}
139 |
140 | fig = go.Figure(data=data, layout=layout)
141 | ```
142 |
143 | ### Example 3 - Multiple Lines Line Chart
144 |
145 |
146 |
147 | ```
148 | colour_scheme = ['red','blue','black','orange','yellow','brown','green']
149 |
150 | # Data
151 | data = []
152 | for day, colour in zip(df['day'].unique(), colour_scheme):
153 | df_temp = df[df['day']==day]
154 | data.append(go.Scatter(x=df_temp['hour'], y=df_temp['customers_count'],
155 | line={'color': colour},
156 | name=day,
157 | mode='lines'))
158 | # Layout
159 | layout = {'title':{'text':'Number of Customer Trend by Days', 'x':0.5}}
160 | ```
161 |
162 | ## Reference
163 | Plotly Documentation Line Chart
--------------------------------------------------------------------------------
/PlotlyExample/LineChart/simple_linechart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/LineChart/simple_linechart.png
--------------------------------------------------------------------------------
/PlotlyExample/LineChart/simple_linechart_points.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/LineChart/simple_linechart_points.png
--------------------------------------------------------------------------------
/PlotlyExample/ParallelCoordinatesPlot/complex_parcoords.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ParallelCoordinatesPlot/complex_parcoords.png
--------------------------------------------------------------------------------
/PlotlyExample/ParallelCoordinatesPlot/complex_pcate.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/grades.csv')
12 | students = df['name'].unique()
13 | num_student = len(students)
14 |
15 | # Prepare colorscale for each line
16 | colours = ['gold','green','red','lightblue','pink']
17 | nums = [num*1.0/(num_student-1) for num in range(0,num_student-1)] + [1.0]
18 |
19 | colourscale_metadata = [[num, colour]
20 | for num, colour in zip(nums , colours)]
21 |
22 | # Prepare labels
23 | labels = df.columns.tolist()[2:]
24 |
25 |
26 | # Prepare the setup of the visualization
27 | fig = go.Figure(data=go.Parcoords(
28 | line={
29 | 'color': df['student_id'],
30 | 'colorscale': colourscale_metadata,
31 | 'showscale': True,
32 | 'cmin':75
33 | },
34 | dimensions=[
35 | {'range':[70,100],
36 | 'constraintrange':[90,101],
37 | 'label': labels[0],
38 | 'values': df[labels[0]]
39 | },
40 | {'range':[70,100],
41 | 'constraintrange':[70,101],
42 | 'label': labels[1],
43 | 'values': df[labels[1]],
44 | 'tickvals':[80, 90, 100],
45 | 'ticktext':['Fair','Great','Excellent']
46 | },
47 | {'range':[70,100],
48 | 'label': labels[2],
49 | 'values': df[labels[2]]
50 | },
51 | {'range':[70,100],
52 | 'label': labels[3],
53 | 'values': df[labels[3]],
54 | 'tickvals':[70, 80, 90, 100],
55 | 'ticktext':['C','B','A','A+']
56 | }
57 | ]
58 | ))
59 |
60 | # Layout
61 | fig.update_layout(
62 | plot_bgcolor = 'white',
63 | paper_bgcolor = 'white'
64 | )
65 |
66 | plotly.offline.plot(fig, filename='advance_pcate.html')
--------------------------------------------------------------------------------
/PlotlyExample/ParallelCoordinatesPlot/readme.md:
--------------------------------------------------------------------------------
1 | # Parallel Coordinates Plot
2 | Parallel Coordinates Plot is a special plot for massive amount of observations to be visualizations different numerical dimensions. In this folder, we will go over how to create a Parallel Coordinates Plot with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
7 | - simple_pcate.py
8 | - complex_pcate.py
9 |
10 |
11 | ## Pacakges Needed
12 | This chapter requires the following packages for the scripts used:
13 |
14 | - Pandas
15 | - Plotly
16 |
17 |
18 | ## Data Used
19 | This chapter may use the following data from the [Data folder](../Data):
20 |
23 |
24 | ## Syntax
25 | ### Data
26 | Data consists of two parts: line and dimensions. line is the setup of line colours and related metadata and whereas dimensions stores the values and attribute related metadata in a list of dictionaries. Parallel Coordinates Plot parameters structure is very different different with standard visualization types. No x or y columns are accepted, but alternative arguements!
27 |
28 | go.Parcoords has the following parameters:
29 |
30 | - line - dictionary of the setting of the lines in the plot
31 |
32 | - color: Accept numbers as label in order to determine what colour to be plotted. IDs or primary keys are good columns to be used
33 | - colorscale: An array of normalized value (0-1.0) mapped to colour, or Plotly reserved words of colorscale
34 | - showscale: True or False to show colour scale as a legend
35 | - cmin: Upper bound of the colour domain, setting the accepted range in the colorcolumn in this dictionary
36 | - cmax: Lower bound of the colour domain, setting the accepted range in the colorcolumn in this dictionary
37 |
38 | - dimensions - array of attribute, each array may consist of:
39 |
40 | - range: The range of this axis
41 | - constraintrange (Optional): select an range within this attribute to be shown on the plot, none if not specify
42 | - label: Attribute value, in string
43 | - values: Value of the data points
44 | - visible: Determine whether this trace is visible. Accept True, False, and 'legendonly'(Trace would not be drawn but appear as a legend item)
45 | - tickvals: To set a interval of the column values
46 | - ticktext: To display the text of the column tickvals alternatively to the original text in the column values
47 |
48 | - unselected - dictionary of setting of the lines are not selected by user or range outside of constraintrange
49 |
50 | - color: The colour of the unselected lines
51 | - Opacity: opacity of the unselected lines, accept values between 0 and 1
52 |
53 |
54 |
55 | ## Example - Parallel Coordinates Plot
56 |
57 |
58 |
59 |
60 |
61 | This is the example of a parallel coordinates plot where constraint range is applied between 70 and 100.
62 |
63 |
64 |
65 |
66 | ```
67 | # Read data
68 | df = pd.read_csv('../Data/grades.csv')
69 | students = df['name'].unique()
70 | num_student = len(students)
71 |
72 | # Prepare colorscale for each line
73 | colours = ['gold','green','red','lightblue','pink']
74 | nums = [num*1.0/(num_student-1) for num in range(0,num_student-1)] + [1.0]
75 |
76 | colourscale_metadata = [[num, colour]
77 | for num, colour in zip(nums , colours)]
78 |
79 | # Prepare labels
80 | labels = df.columns.tolist()[2:]
81 |
82 |
83 | # Prepare the setup of the visualization
84 | fig = go.Figure(data=go.Parcoords(
85 | line={
86 | 'color': df['student_id'],
87 | 'colorscale': colourscale_metadata,
88 | 'showscale': True
89 | },
90 | dimensions=[
91 | {'range':[70,100],
92 | 'constraintrange':[90,101],
93 | 'label': labels[0],
94 | 'values': df[labels[0]]
95 | },
96 | {'range':[70,100],
97 | 'constraintrange':[70,101],
98 | 'label': labels[1],
99 | 'values': df[labels[1]],
100 | 'tickvals':[80, 90, 100],
101 | 'ticktext':['Fair','Great','Excellent']
102 | },
103 | {'range':[70,100],
104 | 'label': labels[2],
105 | 'values': df[labels[2]]
106 | },
107 | {'range':[70,100],
108 | 'label': labels[3],
109 | 'values': df[labels[3]],
110 | 'tickvals':[70, 80, 90, 100],
111 | 'ticktext':['C','B','A','A+']
112 | }
113 | ]
114 | ))
115 |
116 | # Layout
117 | fig.update_layout(
118 | plot_bgcolor = 'white',
119 | paper_bgcolor = 'white'
120 | )
121 | ```
122 |
123 | ## Reference
124 | Plotly Documentation Parallel Coordinates Plot
--------------------------------------------------------------------------------
/PlotlyExample/ParallelCoordinatesPlot/simple_parcoords.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ParallelCoordinatesPlot/simple_parcoords.png
--------------------------------------------------------------------------------
/PlotlyExample/ParallelCoordinatesPlot/simple_parcoords_constrain.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ParallelCoordinatesPlot/simple_parcoords_constrain.png
--------------------------------------------------------------------------------
/PlotlyExample/ParallelCoordinatesPlot/simple_pcate.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/grades.csv')
12 | students = df['name'].unique()
13 | num_student = len(students)
14 |
15 | # Prepare colorscale for each line
16 | colours = ['gold','green','red','lightblue','pink']
17 | nums = [num*1.0/(num_student-1) for num in range(0,num_student-1)] + [1.0]
18 |
19 | colourscale_metadata = [[num, colour]
20 | for num, colour in zip(nums , colours)]
21 |
22 | # Prepare labels
23 | labels = df.columns.tolist()[2:]
24 |
25 |
26 | # Prepare the setup of the visualization
27 | fig = go.Figure(data=go.Parcoords(
28 | line={
29 | 'color': df['student_id'],
30 | 'colorscale': colourscale_metadata
31 | },
32 | dimensions=[
33 | {'range':[70,100],
34 | 'constraintrange':[90,101],
35 | 'label': labels[0],
36 | 'values': df[labels[0]]
37 | },
38 | {'range':[70,100],
39 | 'label': labels[1],
40 | 'values': df[labels[1]]
41 | },
42 | {'range':[70,100],
43 | 'label': labels[2],
44 | 'values': df[labels[2]]
45 | },
46 | {'range':[70,100],
47 | 'label': labels[3],
48 | 'values': df[labels[3]]
49 | }
50 | ]
51 | ))
52 |
53 | # Layout
54 | fig.update_layout(
55 | plot_bgcolor = 'white',
56 | paper_bgcolor = 'white'
57 | )
58 |
59 | plotly.offline.plot(fig, filename='simple_pcate.html')
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/Multiple_pies.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.subplots import make_subplots
5 | from plotly.offline import *
6 |
7 |
8 | # To initiate ploty to run offline
9 | init_notebook_mode(connected=True)
10 | # Import data
11 | df_revenue = pd.read_csv('../Data/revenue_dept.csv')
12 | df_expense = pd.read_csv('../Data/expense_dept.csv')
13 |
14 | # Define fig
15 | fig = make_subplots(rows=1, cols=2, specs=[[{'type':'domain'}, {'type':'domain'}]])
16 |
17 | # Data
18 | # marker colors may added in go.Pie
19 | fig.add_trace(go.Pie(labels=df_revenue['category'],
20 | values=df_revenue['revenue'],name='Revenue'),1,1)
21 | fig.add_trace(go.Pie(labels=df_expense['category'],
22 | values=df_expense['expense'],name='Expense'),1,2)
23 |
24 | # Layout
25 | fig.update_layout(title_text='Department Store Revenue',title_x=0.5)
26 |
27 | plotly.offline.plot(fig, filename='multiple_pies.html')
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/Pretty_pie.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/revenue_dept.csv')
11 |
12 | # Data
13 | colours = ['blue','gold','red','green']
14 | data = []
15 | data.append(go.Pie(labels=df['category'], values=df['revenue'],
16 | hoverinfo='label+percent', textinfo='value', textfont_size=25,
17 | marker={'colors':colours, 'line':{'color':'black','width':3}},
18 | insidetextorientation='radial',pull=[0, 0, 0.3, 0]))
19 |
20 | # Layout
21 | layout = {'title':{'text':'Department Store Revenue', 'x':0.5}}
22 |
23 |
24 | fig = go.Figure(data=data, layout=layout)
25 |
26 | plotly.offline.plot(fig, filename='pretty_pie.html')
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/Simple_donut.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/revenue_dept.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Pie(labels=df['category'], values=df['revenue'], hole=0.4))
15 |
16 | # Layout
17 | layout = {'title':{'text':'Department Store Revenue', 'x':0.5}}
18 |
19 |
20 | fig = go.Figure(data=data, layout=layout)
21 |
22 | plotly.offline.plot(fig, filename='simple_donut.html')
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/Simple_pie.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/revenue_dept.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Pie(labels=df['category'], values=df['revenue']))
15 |
16 | # Layout
17 | layout = {'title':{'text':'Department Store Revenue', 'x':0.5}}
18 |
19 |
20 | fig = go.Figure(data=data, layout=layout)
21 |
22 | plotly.offline.plot(fig, filename='simple_pie.html')
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/multi_pies.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/PieChart/multi_pies.png
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/prettypie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/PieChart/prettypie.png
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/simpledonut.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/PieChart/simpledonut.png
--------------------------------------------------------------------------------
/PlotlyExample/PieChart/simplepie.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/PieChart/simplepie.png
--------------------------------------------------------------------------------
/PlotlyExample/SankeyChart/plotly_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/SankeyChart/plotly_example.png
--------------------------------------------------------------------------------
/PlotlyExample/SankeyChart/plotlyexample_sankey.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 |
11 | fig = go.Figure(data=[go.Sankey(
12 | node = dict(
13 | pad = 15,
14 | thickness = 20,
15 | line = dict(color = "black", width = 0.5),
16 | label = ["A1", "A2", "B1", "B2", "C1", "C2"],
17 | color = ["blue","red","purple","yellow","green","orange"]
18 | ),
19 | link = dict(
20 | source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
21 | target = [2, 3, 3, 4, 4, 5],
22 | value = [8, 4, 2, 8, 4, 2],
23 | color = ["lightblue","pink","lightblue","mediumpurple","lightyellow","lightyellow"]
24 | ))])
25 |
26 | fig.update_layout(title_text="Hello World!")
27 |
28 | plotly.offline.plot(fig, filename='plotlyexample_sankey.html')
29 |
--------------------------------------------------------------------------------
/PlotlyExample/SankeyChart/readme.md:
--------------------------------------------------------------------------------
1 | # Sankey Chart
2 | Sankey chart is a flow diagram which is able to display mutliple dimension from one state to another states.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
7 | - plotlyexample_sankey.py
8 | - simple_sankey.py
9 |
10 |
11 | ## Pacakges Needed
12 | This chapter requires the following packages for the scripts used:
13 |
14 | - Pandas
15 | - Plotly
16 |
17 |
18 |
19 | ## Syntax
20 | ### Data
21 | Data is a list to store go.Sankey(). go.Sankey() consists of two parts: node and link. Sunburst parameters structure is very different different with standard visualization types. No x or y columns are accepted, but alternative arguements!
22 |
23 | go.Sankey() has the following parameters:
24 |
25 | - valueformat: Value format used in the hoverinfo
26 | - valuesuffix: Add suffix after the value displayed in the hoverinfo
27 | - node: Use to display attribute
28 |
29 | - pad: The size of node pad
30 | - thickness: The size of thickness
31 | - label: What to display in the node
32 | - color: Colour filled in the node
33 | - line: Setting of the node line
34 |
35 | - color
36 | - line
37 |
38 |
39 |
40 | - link: Use to display the fact between two attributes
41 |
42 | - source: Start of the link, use the indices of label in node
43 | - target: End of the link, use the indices of label in node
44 | - value: Value of the link
45 | - color: Colour filled in the link
46 |
47 |
48 |
49 |
50 |
51 | ## Plotly Example
52 |
53 |
54 | ```
55 | fig = go.Figure(data=[go.Sankey(
56 | node = dict(
57 | pad = 15,
58 | thickness = 20,
59 | line = dict(color = "black", width = 0.5),
60 | label = ["A1", "A2", "B1", "B2", "C1", "C2"],
61 | color = ["blue","red","purple","yellow","green","orange"]
62 | ),
63 | link = dict(
64 | source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
65 | target = [2, 3, 3, 4, 4, 5],
66 | value = [8, 4, 2, 8, 4, 2],
67 | color = ["lightblue","pink","lightblue","mediumpurple","lightyellow","lightyellow"]
68 | ))])
69 |
70 | fig.update_layout(title_text="Hello World!")
71 | ```
72 |
73 | ## Example - Hours of Video Games Played on Console
74 |
75 |
76 |
77 | See simple_sankey.py for code example.
78 |
79 |
80 | ## Reference
81 | Plotly Documentation Sankey Chart
82 |
--------------------------------------------------------------------------------
/PlotlyExample/SankeyChart/simple_sankey.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/SankeyChart/simple_sankey.png
--------------------------------------------------------------------------------
/PlotlyExample/SankeyChart/simple_sankey.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Define label and its corresponding colours
11 | num2name_colour = {
12 | 0:{'label':'Person 4 Golden','pad_colour':'gold','link_colour':'lightyellow'},
13 | 1:{'label':'Persona 5 Royal','pad_colour':'red','link_colour':'pink'},
14 | 2:{'label':'Altas','pad_colour':'purple','link_colour':'mediumpurple'},
15 | 3:{'label':'Sega','pad_colour':'blue','link_colour':'lightblue'},
16 | 4:{'label':'PS4','pad_colour':'black','link_colour':'lightgray'},
17 | 5:{'label':'PC','pad_colour':'white','link_colour':'lightgray'},
18 | 6:{'label':'Yakuza 7','pad_colour':'yellow','link_colour':'lightyellow'},
19 | 7:{'label':'Flight Simulator','pad_colour':'blue','link_colour':'lavender'}
20 |
21 | }
22 |
23 | fig = go.Figure(data=[go.Sankey(
24 | node = dict(
25 | pad = 15,
26 | thickness = 20,
27 | line = dict(color = "black", width = 0.5),
28 | label = [num2name_colour[k]['label'] for k in num2name_colour],
29 | color = [num2name_colour[k]['pad_colour'] for k in num2name_colour]
30 | ),
31 | link = dict(
32 | source = [0,1,2,3,3,6,7],
33 | target = [2,2,3,4,5,3,5],
34 | value = [400,320,400+320,200+320+120,200,120,250],
35 | color = [num2name_colour[0]['link_colour'],
36 | num2name_colour[1]['link_colour'],
37 | num2name_colour[2]['link_colour'],
38 | num2name_colour[3]['link_colour'],
39 | num2name_colour[3]['link_colour'],
40 | num2name_colour[6]['link_colour'],
41 | num2name_colour[7]['link_colour']
42 | ]
43 | ))])
44 |
45 | fig.update_layout(title_text="Hours of Video Games Played on Console")
46 |
47 | plotly.offline.plot(fig, filename='simple_sankey.html')
48 |
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/Bubblechart.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/tips.csv')
11 |
12 | color_scheme = {'Lunch':'red','Dinner':'blue','Coffee':'brown'}
13 |
14 | meal_type_color = [color_scheme[meal] for meal in df['meal_type'].tolist()]
15 |
16 | # Data
17 | data = []
18 | data.append(go.Scatter(x=df['grand_total'], y=df['tips'],
19 | marker={
20 | 'size': df['wait_mins'],
21 | 'color': meal_type_color
22 | },
23 | mode='markers'))
24 | # Layout
25 | layout = {'title':{'text':'Everybody\'s Tipping Distribution', 'x':0.5}}
26 |
27 | fig = go.Figure(data=data, layout=layout)
28 |
29 | plotly.offline.plot(fig, filename='bubblechart.html')
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/Bubblechart_legend.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/tips.csv')
11 |
12 | color_scheme = {'Lunch': 'red', 'Dinner': 'blue', 'Coffee': 'brown'}
13 |
14 |
15 | # Data
16 | data = []
17 | for meal in df['meal_type'].unique():
18 | df_temp = df[df['meal_type'] == meal]
19 | meal_type_color = [color_scheme[meal]
20 | for meal in df_temp['meal_type'].tolist()]
21 | data.append(go.Scatter(x=df_temp['grand_total'], y=df_temp['tips'],
22 | marker={
23 | 'size': df_temp['wait_mins'],
24 | 'color': meal_type_color
25 | },
26 | name=meal,
27 | mode='markers'))
28 | # Layout
29 | layout = {'title': {'text': 'Everybody\'s Tipping Distribution', 'x': 0.5},
30 | 'legend': {'itemsizing': 'constant'}}
31 |
32 | fig = go.Figure(data=data, layout=layout)
33 |
34 | plotly.offline.plot(fig, filename='bubblechart_legend.html')
35 |
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/CateColourScatterplot.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/tips.csv')
11 |
12 | color_scheme = {'Lunch':'red','Dinner':'blue','Coffee':'brown'}
13 |
14 | meal_type_color = [color_scheme[meal] for meal in df['meal_type'].tolist()]
15 |
16 | # Data
17 | data = []
18 | data.append(go.Scatter(x=df['grand_total'], y=df['tips'],
19 | marker_color=meal_type_color,
20 | mode='markers'))
21 | # Layout
22 | layout = {'title':{'text':'Everybody\'s Tipping Distribution', 'x':0.5}}
23 |
24 | fig = go.Figure(data=data, layout=layout)
25 |
26 | plotly.offline.plot(fig, filename='catedim_scatterplot.html')
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/CateColourScatterplot_legend.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/tips.csv')
11 |
12 | color_scheme = {'Lunch':'red','Dinner':'blue','Coffee':'brown'}
13 |
14 | meal_type_color = [color_scheme[meal] for meal in df['meal_type'].tolist()]
15 |
16 | # Data
17 | data = []
18 | for meal in df['meal_type'].unique():
19 | df_temp = df[df['meal_type']==meal]
20 | data.append(go.Scatter(x=df_temp['grand_total'], y=df_temp['tips'],
21 | marker_color=color_scheme[meal],
22 | name=meal,
23 | mode='markers'))
24 | # Layout
25 | layout = {'title':{'text':'Everybody\'s Tipping Distribution', 'x':0.5}}
26 |
27 | fig = go.Figure(data=data, layout=layout)
28 |
29 | plotly.offline.plot(fig, filename='catedim_scatterplot.html')
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/NumColourScatterplot.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/tips.csv')
11 |
12 |
13 | # Data
14 | data = []
15 | data.append(go.Scatter(x=df['grand_total'], y=df['tips'],
16 | marker_color=df['wait_mins'],
17 | text=df['wait_mins'],
18 | mode='markers'))
19 | # Layout
20 | layout = {'title':{'text':'Everybody\'s Tipping Distribution', 'x':0.5}}
21 |
22 | fig = go.Figure(data=data, layout=layout)
23 |
24 | plotly.offline.plot(fig, filename='numdim_scatterplot.html')
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/SimpleScatterplot.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 | # Import data
10 | df = pd.read_csv('../Data/tips.csv')
11 |
12 | # Data
13 | data = []
14 | data.append(go.Scatter(x=df['grand_total'], y=df['tips'],
15 | mode='markers'))
16 | # Layout
17 | layout = {'title':{'text':'Everybody\'s Tipping Distribution', 'x':0.5}}
18 |
19 | fig = go.Figure(data=data, layout=layout)
20 |
21 | plotly.offline.plot(fig, filename='simple_scatterplot.html')
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/bubblechart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ScatterPlot/bubblechart.png
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/bubblechart_legend.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ScatterPlot/bubblechart_legend.png
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/catedim_scatterplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ScatterPlot/catedim_scatterplot.png
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/catedim_scatterplot_legend.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ScatterPlot/catedim_scatterplot_legend.png
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/numdim_scatterplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ScatterPlot/numdim_scatterplot.png
--------------------------------------------------------------------------------
/PlotlyExample/ScatterPlot/simple_scatterplot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/ScatterPlot/simple_scatterplot.png
--------------------------------------------------------------------------------
/PlotlyExample/SunburstChart/readme.md:
--------------------------------------------------------------------------------
1 | # Sunburst Chart
2 | Sunburst Chart is similar to a treemap but visualize on a pie/donut chart. In this folder, we will go over how to create a sunburst chart with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
7 | - simplesunburst.py
8 | - simplesunburst_colourscale.py
9 |
10 |
11 | ## Pacakges Needed
12 | This chapter requires the following packages for the scripts used:
13 |
14 | - Pandas
15 | - Plotly
16 |
17 |
18 | ## Data Used
19 | This chapter may use the following data from the [Data folder](../Data):
20 |
23 |
24 | ## Syntax
25 | ### Data
26 | Data is a list to store go.Sunburst(). Sunburst parameters structure is very different different with standard visualization types. No x or y columns are accepted, but alternative arguements!
27 |
28 | go.Sunburst() has the following parameters:
29 |
30 | - values: The numeric value of the attribute
31 | - labels: A categorical attribute
32 | - parents: The parent categorical value of labels
33 | - marker_colors: The colour of the area of each attribute
34 | - textinfo: Determines which trace information appear on the graph, it can be:
35 |
36 | - text
37 | - value
38 | - current path
39 | - percent root
40 | - percent entry
41 | - percent parent
42 | - Or any combination of them, simply put a + sign between the values above without white space in between
43 |
44 |
45 | - hoverinfo: What information to be displayed when user hover over the coloured area, all the options are:
46 |
47 | - percent
48 | - label+percent
49 | - label
50 | - name
51 |
52 |
53 |
54 |
55 | ## Example - Simple Sunburst Chart
56 |
57 |
58 | ```
59 | df = pd.read_csv('../Data/salary.csv')
60 |
61 | values = df['salary'].tolist() + [600000,350000]
62 | labels = df['name'].tolist() + df['school'].unique().tolist()
63 | parents = df['school'].tolist() + ['','']
64 |
65 | fig = go.Figure(go.Sunburst(
66 | labels = labels,
67 | values = values,
68 | parents = parents,
69 | textinfo = 'label+value'))
70 |
71 | ```
72 |
73 |
74 | Note: We add two data points in order to demostrate the uniqueness of sunburst chart compared to a pie chart
75 |
76 | Here is the visualization if marker_color is filled with agsunset:
77 |
78 |
79 | ## Reference
80 | Plotly Documentation Sunburst Charts
--------------------------------------------------------------------------------
/PlotlyExample/SunburstChart/simple_sunburst.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/SunburstChart/simple_sunburst.png
--------------------------------------------------------------------------------
/PlotlyExample/SunburstChart/simple_sunburst_agsunset.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/SunburstChart/simple_sunburst_agsunset.png
--------------------------------------------------------------------------------
/PlotlyExample/SunburstChart/simplesunburst.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/hk_population.csv')
12 |
13 | values = df['population'].tolist() + [600000,850000,3000000,0]
14 | labels = df['district'].tolist() + ['Island','Kowloon','New Territories']
15 | parents = df['area'].tolist() + ['Hong Kong','Hong Kong','Hong Kong']
16 |
17 | fig = go.Figure(go.Sunburst(
18 | labels = labels,
19 | values = values,
20 | parents = parents,
21 | textinfo = 'label+value'
22 | ))
23 |
24 |
25 | plotly.offline.plot(fig, filename='simple_sunburst.html')
26 |
--------------------------------------------------------------------------------
/PlotlyExample/SunburstChart/simplesunburst_colourscale.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/hk_population.csv')
12 |
13 | values = df['population'].tolist() + [600000,850000,3000000,0]
14 | labels = df['district'].tolist() + ['Island','Kowloon','New Territories']
15 | parents = df['area'].tolist() + ['Hong Kong','Hong Kong','Hong Kong']
16 |
17 | fig = go.Figure(go.Sunburst(
18 | labels = labels,
19 | values = values,
20 | parents = parents,
21 | textinfo = 'label+value',
22 | marker_colorscale = 'agsunset'
23 | ))
24 |
25 |
26 | plotly.offline.plot(fig, filename='simple_sunburst_agsunset.html')
27 |
--------------------------------------------------------------------------------
/PlotlyExample/Treemap/PlotlyExample_treemap.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 |
11 | values = ["11", "12", "13", "14", "15", "20", "30"]
12 | labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2"]
13 | parents = ["", "A1", "A2", "A3", "A4", "", "B1"]
14 | marker_colours = ["pink", "royalblue", "lightgray", "purple",
15 | "lightgray", "lightblue", "lightgreen"]
16 |
17 | fig = go.Figure(go.Treemap(
18 | labels = labels,
19 | values = values,
20 | parents = parents,
21 | marker_colors = marker_colours,
22 | textinfo = 'label+value+percent parent+percent entry+percent root',
23 | marker_colorscale = 'Blues'))
24 |
25 |
26 | plotly.offline.plot(fig, filename='plotly_example_tree.html')
--------------------------------------------------------------------------------
/PlotlyExample/Treemap/SalaryExample_treemap.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from plotly.offline import *
5 |
6 |
7 | # To initiate ploty to run offline
8 | init_notebook_mode(connected=True)
9 |
10 | # Read data
11 | df = pd.read_csv('../Data/salary.csv')
12 |
13 | values = df['salary'].tolist() + [0,0]
14 | labels = df['name'].tolist() + df['school'].unique().tolist()
15 | parents = df['school'].tolist() + ['','']
16 |
17 | fig = go.Figure(go.Treemap(
18 | labels = labels,
19 | values = values,
20 | parents = parents,
21 | textinfo = 'label+value+percent parent+percent entry+percent root',
22 | marker_colorscale = 'Blues'))
23 |
24 |
25 | plotly.offline.plot(fig, filename='salary_example_tree.html')
26 |
--------------------------------------------------------------------------------
/PlotlyExample/Treemap/plotly_treemap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Treemap/plotly_treemap.png
--------------------------------------------------------------------------------
/PlotlyExample/Treemap/readme.md:
--------------------------------------------------------------------------------
1 | # Treemap
2 | Treemap. In this folder, we will go over how to create a treemap with Python and Plotly.
3 |
4 | ## Files
5 | The following scripts are used in this chapter:
6 |
7 | - PlotlyExample_treemap.py
8 | - SalaryExample_treemap.py
9 |
10 |
11 | ## Pacakges Needed
12 | This chapter requires the following packages for the scripts used:
13 |
14 | - Pandas
15 | - Plotly
16 |
17 |
18 | ## Data Used
19 | This chapter may use the following data from the [Data folder](../Data):
20 |
23 |
24 | ## Syntax
25 | ### Data
26 | Data is a list to store go.Treemap(). Treemap parameters structure is very different different with standard visualization types. No x or y columns are accepted, but alternative arguements!
27 |
28 | go.Treemap() has the following parameters:
29 |
30 | - values: The numeric value of the attribute
31 | - labels: A categorical attribute
32 | - parents: The parent categorical value of labels
33 | - textinfo: Determines which trace information appear on the graph, it can be:
34 |
35 | - text
36 | - value
37 | - current path
38 | - percent root
39 | - percent entry
40 | - percent parent
41 | - Or any combination of them, simply put a + sign between the values above without white space in between
42 |
43 |
44 | - marker_colors: The colour of the area of each attribute
45 | - hoverinfo: What information to be displayed when user hover over the coloured area, all the options are:
46 |
47 | - percent
48 | - label+percent
49 | - label
50 | - name
51 |
52 |
53 |
54 |
55 |
56 | ## Tips
57 |
58 | - x, y, z can not be pass as parameters
59 | - layout is not working in go.Treemap() as expected
60 | - All attribute requires parent value and simply passing a Pandas dataframe column would not work, you may add the root value at the end of the array of values and an empty value at the end of the array of parents
61 |
62 |
63 |
64 |
65 | ## Examples
66 | ### Example 1 - Treemap from Plotly
67 |
68 |
69 | ```
70 | values = ["11", "12", "13", "14", "15", "20", "30"]
71 | labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2"]
72 | parents = ["", "A1", "A2", "A3", "A4", "", "B1"]
73 | marker_colours = ["pink", "royalblue", "lightgray", "purple",
74 | "lightgray", "lightblue", "lightgreen"]
75 |
76 | fig = go.Figure(go.Treemap(
77 | labels = labels,
78 | values = values,
79 | parents = parents,
80 | marker_colors = marker_colours,
81 | textinfo = 'label+value+percent parent+percent entry+percent root',
82 | marker_colorscale = 'Blues'))
83 | ```
84 | ### Example 2 - Treemap with Salary Dataset
85 |
86 |
87 | ```
88 | df = pd.read_csv('../Data/salary.csv')
89 |
90 | values = df['salary'].tolist() + [0,0]
91 | labels = df['name'].tolist() + df['school'].unique().tolist()
92 | parents = df['school'].tolist() + ['','']
93 |
94 | data = go.Figure(go.Treemap(
95 | labels = labels,
96 | values = values,
97 | parents = parents,
98 | textinfo = 'label+value+percent parent+percent entry+percent root',
99 | marker_colorscale = 'Blues'))
100 | ```
101 |
102 | ## Reference
103 | Plotly Documentation
104 |
--------------------------------------------------------------------------------
/PlotlyExample/Treemap/salary_treemap.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jacquessham/DashExamples/d0614c6d3fd7ec7a7b905830edf79900435b2cde/PlotlyExample/Treemap/salary_treemap.png
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/.gitignore:
--------------------------------------------------------------------------------
1 | # For Testing
2 | arguements_testing.json
3 | testing_call_plotly.py
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/aggregatedhistogram_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/salary.csv",
3 | "viz_type":"histogram",
4 | "viz_name":"Salary Distribution",
5 | "metadata":{
6 | "x":"salary",
7 | "cate_col":"school",
8 | "viz_subtype":"aggregated_histogram",
9 | "barmode":"stack",
10 | "histfunc":"sum"
11 | }
12 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/boxplot_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"salary.csv",
3 | "viz_type":"boxplot",
4 | "viz_name":"Salary by School",
5 | "metadata":{
6 | "x":"school",
7 | "y":"salary"
8 | }
9 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/bubblechart_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/tips.csv",
3 | "viz_type":"bubblechart",
4 | "viz_name":"Tipping Distribution",
5 | "metadata":{
6 | "x":"grand_total",
7 | "y":"tips",
8 | "colour":"meal_type",
9 | "size":"wait_mins",
10 | "showlegend":true,
11 | "colour_schema":{
12 | "Lunch":"red",
13 | "Dinner":"blue",
14 | "Coffee":"brown"
15 | },
16 | "constant_itemsizing":false,
17 | "addition_colourscale":{
18 | "low":"rgb(110, 0, 255)",
19 | "high":"rgb(0, 110, 0)"
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/candlestick_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"",
3 | "viz_type":"",
4 | "viz_name":"",
5 | "metadata":{
6 | "x":"",
7 | "y":"",
8 | "viz_subtype":""
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/catecolour_scatter_arguement.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/tips.csv",
3 | "viz_type":"scatter",
4 | "viz_name":"Tipping Distribution",
5 | "metadata":{
6 | "x":"grand_total",
7 | "y":"tips",
8 | "z":"meal_type",
9 | "viz_subtype":"cate_color",
10 | "showlegend":false,
11 | "colour_scheme":{
12 | "Lunch":"red",
13 | "Dinner":"blue",
14 | "Coffee":"brown"
15 | },
16 | "addition_colourscale":{
17 | "low":"rgb(110, 0, 255)",
18 | "high":"rgb(0, 110, 0)"
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/catehistogram_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/salary.csv",
3 | "viz_type":"histogram",
4 | "viz_name":"Salary Distribution",
5 | "metadata":{
6 | "x":"salary",
7 | "cate_col":"school",
8 | "viz_subtype":"cate_histogram",
9 | "cumulative":false,
10 | "barmode":"stack"
11 | }
12 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/complexbar_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/testing_expense_everybody.csv",
3 | "viz_type":"bar",
4 | "viz_name":"Expense by Person",
5 | "metadata":{
6 | "x":"name",
7 | "y":"amount",
8 | "cate_col":"expense_category",
9 | "viz_subtype":"stack"
10 | }
11 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/horizontalbar_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/salary.csv",
3 | "viz_type":"bar",
4 | "viz_name":"Salary by Name",
5 | "metadata":{
6 | "y":"name",
7 | "x":"salary",
8 | "viz_subtype":"horizontal"
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/multilines_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/cust_num.csv",
3 | "viz_type":"line",
4 | "viz_name":"Trend",
5 | "metadata":{
6 | "x":"hour",
7 | "y":"customers_count",
8 | "cate_col":"day",
9 | "viz_subtype":"multilines",
10 | "line_colour":{
11 | "Monday":"red",
12 | "Tuesday":"blue",
13 | "Wednesday":"black",
14 | "Thursday":"orange",
15 | "Friday":"yellow",
16 | "Saturday":"brown",
17 | "Sunday":"green"
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/normalizedhistogram_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/salary.csv",
3 | "viz_type":"histogram",
4 | "viz_name":"Salary Distribution",
5 | "metadata":{
6 | "x":"salary",
7 | "viz_subtype":"normalised",
8 | "histnorm":"probability",
9 | "cumulative":true
10 | }
11 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/numcolour_scatter_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/tips.csv",
3 | "viz_type":"scatter",
4 | "viz_name":"Tipping Distribution",
5 | "metadata":{
6 | "x":"grand_total",
7 | "y":"tips",
8 | "z":"wait_mins",
9 | "showscale":"false",
10 | "colour_scale":"Viridis",
11 | "viz_subtype":"num_color"
12 | }
13 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simplebar_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"salary.csv",
3 | "viz_type":"bar",
4 | "viz_name":"Salary by Name",
5 | "metadata":{
6 | "x":"name",
7 | "y":"salary",
8 | "viz_subtype":"simple"
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simplefunnel_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/ecom_funnel.csv",
3 | "viz_type":"funnel chart",
4 | "viz_name":"Ecommerce Conversion Funnel Chart",
5 | "metadata":{
6 | "y":"stage",
7 | "x":"stage",
8 | "viz_subtype":"simple_funnel"
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simplefunnelarea_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/ecom_funnel.csv",
3 | "viz_type":"funnel chart",
4 | "viz_name":"Ecommerce Conversion Funnel Chart",
5 | "metadata":{
6 | "label":"stage",
7 | "text":"stage",
8 | "values":"count",
9 | "viz_subtype":"simple_funnelarea"
10 | }
11 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simpleheatmap_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/cust_num.csv",
3 | "viz_type":"heatmap",
4 | "viz_name":"Department Store Traffic",
5 | "metadata":{
6 | "x":"day",
7 | "y":"hour",
8 | "colour":"customers_count"
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simplehistogram_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/salary.csv",
3 | "viz_type":"histogram",
4 | "viz_name":"Salary Distribution",
5 | "metadata":{
6 | "x":"salary",
7 | "viz_subtype":"simple"
8 | }
9 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simpleline_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/cust_num.csv",
3 | "viz_type":"line",
4 | "viz_name":"Trend",
5 | "metadata":{
6 | "x":"hour",
7 | "y":"customers_count",
8 | "viz_subtype":"simple"
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simplepie_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/revenue_dept.csv",
3 | "viz_type":"pie chart",
4 | "viz_name":"Department Store Revenue Distribution",
5 | "metadata":{
6 | "x":"category",
7 | "y":"revenue",
8 | "hole":0.4,
9 | "textinfo":"label+percent"
10 | }
11 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/simplescatter_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/tips.csv",
3 | "viz_type":"scatter",
4 | "viz_name":"Tipping Distribution",
5 | "metadata":{
6 | "x":"grand_total",
7 | "y":"tips",
8 | "viz_subtype":"simple"
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/TemplateExamples/stackfunnel_arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"../PlotlyExample/Data/ecom_funnel.csv",
3 | "viz_type":"funnel chart",
4 | "viz_name":"Ecommerce Conversion Funnel Chart",
5 | "metadata":{
6 | "x":"count",
7 | "y":"stage",
8 | "viz_subtype":"stack_funnel",
9 | "category":"shop"
10 | }
11 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/arguements.json:
--------------------------------------------------------------------------------
1 | {
2 | "df_directory":"",
3 | "viz_type":"",
4 | "viz_name":"",
5 | "metadata":{
6 | "x":"",
7 | "y":"",
8 | "viz_subtype":""
9 | }
10 | }
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/call_plotly.py:
--------------------------------------------------------------------------------
1 | import json
2 | import pandas as pd
3 | import plotly
4 | import plotly.graph_objs as go
5 | from plotly.offline import *
6 | from generate_plotly import *
7 |
8 |
9 | with open('arguements.json') as f:
10 | args = json.load(f)
11 | df = pd.read_csv(args['df_directory'])
12 | fig = generate_plotly_viz(
13 | df, args['metadata'], args['viz_type'], args['viz_name'])
14 | plotly.offline.plot(fig, filename='call_plotly.html')
15 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/check_metadata.py:
--------------------------------------------------------------------------------
1 | ### Universal Viz Arg
2 | def check_text(metadata):
3 | if 'text' in metadata:
4 | return metadata['text']
5 | return None
6 |
7 | ### Universal Viz Arg
8 | def check_textposition(metadata):
9 | if 'textposition' in metadata:
10 | return metadata['textposition']
11 | elif 'text_position' in metadata:
12 | return metadata['text_position']
13 | return None
14 |
15 | ### Universal Viz Arg
16 | def check_hoverinfo(metadata):
17 | if 'hoverinfo' in metadata:
18 | return metadata['hoverinfo']
19 | return 'none' # To turn it off
20 |
21 | ### Universal Viz Arg
22 | def check_name(metadata):
23 | if 'name' in metadata:
24 | return metadata['name']
25 | return None
26 |
27 | ### Bar Arg
28 | def check_width(metadata):
29 | if 'width' in metadata:
30 | return metadata['width']
31 | return None
32 |
33 | ### Bar, Boxplot Arg
34 | def check_textfont(metadata):
35 | if 'textfont' in metadata:
36 | return metadata['textfont']
37 | elif 'text_font' in metadata:
38 | return metadata['text_font']
39 | return None
40 |
41 | ### Bar, Boxplot Arg
42 | def check_barcolour(metadata):
43 | # Allow user to spell English and American English and use of _
44 | if 'barcolour' in metadata:
45 | return metadata['barcolour']
46 | elif 'bar_colour' in metadata:
47 | return metadata['bar_colour']
48 | elif 'barcolor' in metadata:
49 | return metadata['barcolor']
50 | elif 'bar_color' in metadata:
51 | return metadata['bar_color']
52 | return None
53 |
54 | ### Bar, Line, Histogram, Funnel Chart Arg
55 | def check_cate_col(metadata):
56 | if 'cate_col' in metadata:
57 | return metadata['cate_col']
58 | elif 'category_column' in metadata:
59 | return metadata['category_column']
60 | elif 'category_col' in metadata:
61 | return metadata['category_col']
62 | elif 'category' in metadata:
63 | return metadata['category']
64 | return None
65 |
66 | ### Boxplot Arg
67 | def check_boxmean(metadata):
68 | if 'boxmean' in metadata:
69 | return metadata['boxmean']
70 | return None
71 |
72 | ### Line Chart
73 | # Return a boolean value
74 | def check_datapoints(metadata):
75 | if 'datapoints' in metadata:
76 | return metadata['datapoints'] in ['t', 'true', 'True']
77 | elif 'data_points' in metadata:
78 | return metadata['data_points'] in ['t', 'true', 'True']
79 | return False
80 |
81 | ### Line Chart
82 | def check_line_colour(metadata):
83 | if 'line_colour' in metadata:
84 | return metadata['line_colour']
85 | elif 'line_color' in metadata:
86 | return metadata['line_color']
87 | return None
88 |
89 | ### Scatterplot/Bubble Chart, Heatmap
90 | def check_colourscale(metadata):
91 | if 'colourscale' in metadata:
92 | return metadata['colourscale']
93 | elif 'colorscale' in metadata:
94 | return metadata['colorscale']
95 | elif 'colour_scale' in metadata:
96 | return metadata['colour_scale']
97 | elif 'color_scale' in metadata:
98 | return metadata['color_scale']
99 | return None
100 |
101 | ### Scatterplot/Bubble Chart
102 | def check_add_colourscale(metadata):
103 | if 'addition_colourscale' in metadata:
104 | return metadata['addition_colourscale']
105 | elif 'addition_colorscale' in metadata:
106 | return metadata['addition_colorscale']
107 | return None
108 |
109 | ### Scatterplot/Bubble Chart
110 | def check_colour_scheme(metadata):
111 | if 'colour_scheme' in metadata:
112 | return metadata['colour_scheme']
113 | elif 'color_scheme' in metadata:
114 | return metadata['color_scheme']
115 | elif 'colour_choices' in metadata:
116 | return metadata['colour_choices']
117 | elif 'colour_choices' in metadata:
118 | return metadata['color_choices']
119 | return None
120 |
121 | ### Scatterplot/Bubble Chart
122 | # Return a boolean value
123 | def check_showlegend(metadata):
124 | if 'showlegend' in metadata:
125 | return metadata['showlegend'] in ['t','true','True', True]
126 | return True # Should show showscale by default
127 |
128 | ### Scatterplot/Bubble Chart
129 | # Return a boolean value
130 | def check_showscale(metadata):
131 | if 'showscale' in metadata:
132 | return metadata['showscale'] in ['t','true','True', True]
133 | return True # Should show showscale by default
134 |
135 | ### Histogram
136 | def check_histnorm(metadata):
137 | if 'histnorm' in metadata:
138 | return metadata['histnorm']
139 | return None
140 |
141 | ### Histogram
142 | def check_cumulative_enabled(metadata):
143 | if 'cumulative' in metadata:
144 | return metadata['cumulative'] in ['t','true','True', True]
145 | elif 'cumulative_enabled' in metadata:
146 | return metadata['cumulative_enabled'] in ['t','true','True', True]
147 | return False
148 |
149 | ### Histogram
150 | def check_histfunc(metadata):
151 | if 'histfunc' in metadata:
152 | return metadata['histfunc']
153 | return 'count' # By default, return count
154 |
155 | ### Pie/Donut Chart
156 | def check_hole(metadata):
157 | if 'hole' in metadata:
158 | return metadata['hole']
159 | elif 'radius' in metadata:
160 | return metadata['radius']
161 | return None
162 |
163 | ### Pie/Donut Chart
164 | def check_textinfo(metadata):
165 | if 'textinfo' in metadata:
166 | return metadata['textinfo']
167 | return 'percent'
168 |
169 |
170 | ### Funnel Chart
171 | def check_marker(metadata):
172 | if 'marker' in metadata:
173 | return metadata['marker']
174 | return None
175 |
176 | def check_connector(metadata):
177 | if 'connector' in metadata:
178 | return metadata['connector']
179 | return None
180 |
181 | def check_textinfo(metadata):
182 | if 'textinfo' in metadata:
183 | return metadata['textinfo']
184 | return 'value'
185 |
186 | def check_labels(metadata):
187 | if 'labels' in metadata:
188 | return metadata['labels']
189 | return None
190 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/css_colours.py:
--------------------------------------------------------------------------------
1 | css_colours = ['aqua',
2 | 'aquamarine',
3 | 'bisque',
4 | 'black',
5 | 'blanchedalmond',
6 | 'blue',
7 | 'blueviolet',
8 | 'brown',
9 | 'burlywood',
10 | 'cadetblue',
11 | 'chartreuse',
12 | 'chocolate',
13 | 'coral',
14 | 'cornflowerblue',
15 | 'crimson',
16 | 'cyan',
17 | 'darkblue',
18 | 'darkcyan',
19 | 'darkgoldenrod',
20 | 'darkgray',
21 | 'darkgrey',
22 | 'darkgreen',
23 | 'darkkhaki',
24 | 'darkmagenta',
25 | 'darkolivegreen',
26 | 'darkorange',
27 | 'darkorchid',
28 | 'darkred',
29 | 'darksalmon',
30 | 'darkseagreen',
31 | 'darkslateblue',
32 | 'darkslategray',
33 | 'darkslategrey',
34 | 'darkturquoise',
35 | 'darkviolet',
36 | 'deeppink',
37 | 'deepskyblue',
38 | 'dimgray',
39 | 'dimgrey',
40 | 'dodgerblue',
41 | 'firebrick',
42 | 'forestgreen',
43 | 'fuchsia',
44 | 'gainsboro',
45 | 'gold',
46 | 'goldenrod',
47 | 'gray',
48 | 'grey',
49 | 'green',
50 | 'greenyellow',
51 | 'hotpink',
52 | 'indianred',
53 | 'indigo',
54 | 'khaki',
55 | 'lavender',
56 | 'lawngreen',
57 | 'lightblue',
58 | 'lightcoral',
59 | 'lightcyan',
60 | 'lightgray',
61 | 'lightgrey',
62 | 'lightgreen',
63 | 'lightpink',
64 | 'lightsalmon',
65 | 'lightseagreen',
66 | 'lightskyblue',
67 | 'lightslategray',
68 | 'lightslategrey',
69 | 'lightsteelblue',
70 | 'lime',
71 | 'limegreen',
72 | 'magenta',
73 | 'maroon',
74 | 'mediumaquamarine',
75 | 'mediumblue',
76 | 'mediumorchid',
77 | 'mediumpurple',
78 | 'mediumseagreen',
79 | 'mediumslateblue',
80 | 'mediumspringgreen',
81 | 'mediumturquoise',
82 | 'mediumvioletred',
83 | 'midnightblue',
84 | 'mistyrose',
85 | 'moccasin',
86 | 'navy',
87 | 'olive',
88 | 'olivedrab',
89 | 'orange',
90 | 'orangered',
91 | 'orchid',
92 | 'palegoldenrod',
93 | 'palegreen',
94 | 'paleturquoise',
95 | 'palevioletred',
96 | 'peru',
97 | 'pink',
98 | 'plum',
99 | 'powderblue',
100 | 'purple',
101 | 'red',
102 | 'rosybrown',
103 | 'royalblue',
104 | 'rebeccapurple',
105 | 'saddlebrown',
106 | 'salmon',
107 | 'sandybrown',
108 | 'seagreen',
109 | 'sienna',
110 | 'silver',
111 | 'skyblue',
112 | 'slateblue',
113 | 'slategray',
114 | 'slategrey',
115 | 'springgreen',
116 | 'steelblue',
117 | 'tan',
118 | 'teal',
119 | 'thistle',
120 | 'tomato',
121 | 'turquoise',
122 | 'violet',
123 | 'wheat',
124 | 'yellow',
125 | 'yellowgreen']
126 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_bar.py:
--------------------------------------------------------------------------------
1 | import plotly
2 | import plotly.graph_objs as go
3 |
4 |
5 | """ Function to prepare data list in data.py for simple bar chart """
6 | def generate_simplebar(x, y, text=None, bar_colour=None, width=None,
7 | textposition='auto', textfont={'color': 'white'},
8 | hoverinfo='none'):
9 | return go.Bar(x=x, y=y, width=width,
10 | text=text, textposition=textposition,
11 | marker_color=bar_colour, textfont=textfont,
12 | hoverinfo=hoverinfo)
13 |
14 | """ Function to prepare data list in data.py for horizontal bar chart """
15 | def generate_hbar(x, y, text=None, bar_colour=None, width=None,
16 | textposition='auto', textfont={'color': 'white'},
17 | hoverinfo='none'):
18 | return go.Bar(x=x, y=y, width=width,
19 | text=text, textposition=textposition,
20 | marker_color=bar_colour, textfont=textfont,
21 | orientation='h', hoverinfo=hoverinfo)
22 |
23 |
24 | """ Function to prepare data list in data.py for group or stack bar chart """
25 | def generate_complexbar(df, x, y, cate_col, text=None, bar_colour=None,
26 | width=None, textposition='auto',
27 | textfont={'color': 'white'}, hoverinfo='none'):
28 | data = []
29 | if bar_colour is None:
30 | for cate in df[cate_col].unique():
31 | df_temp = df[df[cate_col] == cate]
32 | data.append(
33 | go.Bar(
34 | name=cate,
35 | x=df_temp[x], y=df_temp[y],
36 | width=width,
37 | text=text, textposition=textposition,
38 | textfont=textfont, hoverinfo=hoverinfo
39 | )
40 | )
41 |
42 | else:
43 | for cate, colour in zip(df[cate_col].unique(), bar_colour):
44 | df_temp = df[df[cate_col] == cate]
45 | data.append(
46 | go.Bar(
47 | name=cate, x=df_temp[x], y=df_temp[y],
48 | marker_color=colour,
49 | text=text, textposition=textposition,
50 | textfont=textfont, hoverinfo=hoverinfo
51 | )
52 | )
53 | return data
54 |
55 |
56 | def barmode_add2_layout(layout, barmode):
57 | """ Function to add metadata in layout.py for group or stack bar chart
58 | """
59 | # "simple" is not a Plotly option
60 | if barmode == 'simple' or barmode == 'horizontal':
61 | return layout
62 | layout['barmode'] = barmode
63 | return layout
64 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_boxplot.py:
--------------------------------------------------------------------------------
1 | import plotly
2 | import plotly.graph_objs as go
3 |
4 |
5 | def generate_boxplot(df, category_col, y_col,
6 | bar_colour=None, boxmean=None, textposition='auto'):
7 | # Check len of bar_colour is same as len category_col, would fail if not
8 | if bar_colour is not None and len(bar_colour) != category_col:
9 | bar_colour = None
10 |
11 | # Prepare Data
12 | data = []
13 |
14 | for category in df[category_col].unique():
15 | df_temp = df[df[category_col] == category]
16 | data.append(
17 | go.Box(
18 | y=df_temp[y_col],
19 | name=category,
20 | marker_color=bar_colour,
21 | boxmean=boxmean
22 | )
23 | )
24 |
25 | return data
26 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_candlestick.py:
--------------------------------------------------------------------------------
1 | import plotly
2 | import plotly.graph_objs as go
3 |
4 |
5 | """ Function to prepare data list in data.py for candlestick chart """
6 | def generate_candlestick(x, open_price, high_price, low_price, close_price):
7 | return go.Candlestick(x=x, open=open_price, high=high_price, low=low_price,
8 | close=close_price)
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_funnel.py:
--------------------------------------------------------------------------------
1 | import plotly
2 | import plotly.graph_objs as go
3 |
4 |
5 | """ Function to prepare data list in data.py for simple funnel chart """
6 | def generate_simplefunnel(x, y, marker=None, connector=None,
7 | textposition='auto', textinfo='value',
8 | hoverinfo='none'):
9 | return go.Funnel(x=x, y=y, marker=marker, connector=connector,
10 | textposition=textposition, textinfo=textinfo,
11 | hoverinfo=hoverinfo)
12 |
13 | """ Function to prepare data list in data.py for stack funnel chart """
14 | def generate_stackfunnel(df, x, y, cate_col, marker=None,
15 | connector=None, textposition='auto',
16 | textinfo='value', hoverinfo='none'):
17 | data = []
18 | for cate in df[cate_col].unique():
19 | df_temp = df[df[cate_col] == cate]
20 | data.append(
21 | go.Funnel(
22 | name=cate,
23 | x=df_temp[x], y=df_temp[y], marker=marker,
24 | connector=connector, textposition=textposition,
25 | textinfo=textinfo, hoverinfo=hoverinfo
26 | )
27 | )
28 | return data
29 |
30 | """ Function to prepare data list in data.py for simple funnel area chart """
31 | def generate_simplefunnelarea(values, text=None, labels=None, marker=None,
32 | textposition='auto', textinfo='value',
33 | hoverinfo='none'):
34 | return go.Funnelarea(text=text, labels=labels, values=values,
35 | marker=marker, textposition=textposition,
36 | textinfo=textinfo, hoverinfo=hoverinfo)
37 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_heatmap.py:
--------------------------------------------------------------------------------
1 | import plotly
2 | import plotly.graph_objs as go
3 |
4 |
5 | def generate_heatmap(x, y, z, colourscale, hoverinfo='none'):
6 | if colourscale is None:
7 | colourscale = 'ylorrd'
8 | return go.Heatmap(z=z, x=z, y=y,colorscale=colourscale,
9 | hoverinfo=hoverinfo)
10 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_histogram.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 |
5 |
6 | def generate_simplehistogram(x, histnorm=None, cumulative_enabled=False):
7 | return go.Histogram(x=x, histnorm=histnorm,
8 | cumulative_enabled=cumulative_enabled)
9 |
10 | def generate_categoricalhistogram(df, x_col, cate_col,
11 | cumulative_enabled=False):
12 | data = []
13 | for group in df[cate_col].unique():
14 | df_temp = df[df[cate_col]==group]
15 | data.append(go.Histogram(x=df_temp[x_col], name=group,
16 | cumulative_enabled=cumulative_enabled))
17 | return data
18 |
19 | def generate_aggregatedhistogram(df, x_col, cate_col, histfunc='count',
20 | cumulative_enabled=False):
21 | data = []
22 | for group in df[cate_col].unique():
23 | df_temp = df[df[cate_col]==group]
24 | data.append(go.Histogram(x=df_temp[x_col], y=df_temp[x_col],
25 | histfunc=histfunc, name=group,
26 | cumulative_enabled=cumulative_enabled))
27 | return data
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_line.py:
--------------------------------------------------------------------------------
1 | import plotly
2 | import plotly.graph_objs as go
3 |
4 |
5 | def get_mode(datapoints):
6 | if datapoints:
7 | return 'lines+markers'
8 | return 'lines'
9 |
10 | def generate_simpleline(x, y, datapoints=False, hoverinfo='none'):
11 | mode = get_mode(datapoints)
12 | return go.Scatter(x=x, y=y, mode=mode, hoverinfo=hoverinfo)
13 |
14 | def generate_multiplelines(x, y, name, line_colours,
15 | datapoints=False, hoverinfo='none'):
16 | mode = get_mode(datapoints)
17 | data =[]
18 |
19 | # x, y themselves should have partitioned already
20 | for x_i, y_i, name_i, colour in zip(x, y, name, line_colours):
21 | data.append(go.Scatter(x=x_i, y=y_i, mode=mode, name=name_i,
22 | hoverinfo=hoverinfo, line={'color': colour}))
23 |
24 | return data
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_pie.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 |
5 |
6 | def generate_simplepie(x, y, hole=0, textinfo='percent',hoverinfo='none'):
7 | return go.Pie(labels=x, values=y, hole=hole, textinfo=textinfo, hoverinfo=hoverinfo)
8 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_plotly.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import plotly
3 | import plotly.graph_objs as go
4 | from data import *
5 | from layout import *
6 |
7 |
8 | """ Prepare data and layout, and return the figure object to render
9 | with Plotly
10 | """
11 | def generate_plotly_viz(df, metadata, viz_type, viz_name):
12 | data = generate_plotlydata(df, metadata, viz_type)
13 | layout = generate_layout(viz_type, metadata, title=viz_name)
14 |
15 | fig = go.Figure(data=data, layout=layout)
16 | return fig
17 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/generate_scatterplot.py:
--------------------------------------------------------------------------------
1 | from random import choices
2 | import pandas as pd
3 | import plotly
4 | import plotly.graph_objs as go
5 | import plotly.express as px
6 | from css_colours import css_colours
7 |
8 |
9 | # Helper function for mapping colour scheme
10 | def prepare_colour_scheme(z_unique_val, z_unique_val_n, colour_choices):
11 | # Verify if colour_scheme is provided by users
12 | if colour_choices is not None:
13 | if type(colour_choices) is dict:
14 | colour_scheme = colour_choices
15 | elif type(colour_choices) is list:
16 | colour_scheme = {z_val: colour
17 | for z_val, colour in zip(z_unique_val, colour_choices)}
18 | # If users did not provide
19 | else:
20 | # If distinct number of labels equal or less than 10
21 | if z_unique_val_n <= 10:
22 | colour_choices = px.colors.qualitative.Plotly[:z_unique_val_n]
23 | # If distinct number of labels equal more than 10 but not many
24 | elif z_unique_val_n <= len(css_colours):
25 | colour_choices = choices(css_colours, k=z_unique_val_n)
26 | # If distinct number of labels are too much
27 | else:
28 | if addition_colorscale is not None:
29 | colour_choices = plotly.colors.n_colors(
30 | addition_colorscale['low'], addition_colorscale['high'],
31 | z_unique_val_n, colortype='rgb'
32 | )
33 | else:
34 | colour_choices = plotly.colors.n_colors('rgb(0, 0, 255)',
35 | 'rgb(255, 0, 0)', z_unique_val_n, colortype='rgb')
36 | colour_scheme = {z_val: colour
37 | for z_val, colour in zip(z_unique_val, colour_choices)}
38 | return colour_scheme
39 |
40 | def generate_simplescatter(x, y, hoverinfo='none'):
41 | return go.Scatter(x=x, y=y, hoverinfo=hoverinfo,
42 | mode='markers')
43 |
44 | def generate_numcolour_scatter(x, y, z, showscale=True, colorscale=None,
45 | hoverinfo='none'):
46 | marker_config = {'color':z, 'showscale':showscale}
47 | if colorscale is not None:
48 | marker_config['colorscale'] = colorscale
49 | return go.Scatter(x=x, y=y, mode='markers', hoverinfo=hoverinfo,
50 | marker=marker_config)
51 |
52 | def generate_catecolour_scatter(x, y, z, showlegend=True, colour_choices=None,
53 | addition_colorscale=None, hoverinfo='none'):
54 | # Figure out the colour scheme mapping first
55 | z_unique_val = z.unique().tolist()
56 | z_unique_val_n = len(z_unique_val)
57 |
58 | colour_scheme = prepare_colour_scheme(z_unique_val, z_unique_val_n,
59 | colour_choices)
60 |
61 | # Prepare data list and partition by label
62 | data = []
63 | for z_val in z_unique_val:
64 | i_temp = [i for i in z.index if z[i]==z_val]
65 | x_val = x.iloc[i_temp]
66 | y_val = y.iloc[i_temp]
67 | data.append(go.Scatter(x=x_val, y=y_val,
68 | marker_color=colour_scheme[z_val], name=z_val, mode='markers',
69 | showlegend=showlegend, hoverinfo=hoverinfo))
70 |
71 | return data
72 |
73 | def generate_bubble_chart(x, y, z_dict, showlegend=True, colour_choices=None,
74 | addition_colorscale=None, hoverinfo='none'):
75 | data = []
76 | # When colour is needed, convert it to label
77 | if 'colour' in z_dict:
78 | # Figure out the colour scheme mapping first
79 | colour_unique_val = z_dict['colour'].unique().tolist()
80 | colour_unique_val_n = len(colour_unique_val)
81 | colour_scheme = prepare_colour_scheme(colour_unique_val,
82 | colour_unique_val_n, colour_choices)
83 | for colour_val in colour_unique_val:
84 | i_temp = [i for i in z_dict['colour'].index
85 | if z_dict['colour'][i]==colour_val]
86 | x_val = x.iloc[i_temp]
87 | y_val = y.iloc[i_temp]
88 | marker_config = {'color': [colour_scheme[colour_val]]*len(x_val)}
89 | if 'size' in z_dict:
90 | marker_config['size'] = z_dict['size'].iloc[i_temp]
91 | data.append(go.Scatter(x=x_val, y=y_val, name=colour_val,
92 | marker=marker_config, mode='markers', showlegend=showlegend,
93 | hoverinfo=hoverinfo))
94 | # When colour is not needed, simply pass all parameters to plotly
95 | else:
96 | data.append(go.Scatter(x=x, y=y, marker={'size':z_dict['size']},
97 | mode='markers', showlegend=showlegend, hoverinfo=hoverinfo))
98 | return data
99 |
100 |
--------------------------------------------------------------------------------
/PlotlyTemplateFramework/layout.py:
--------------------------------------------------------------------------------
1 | from generate_bar import barmode_add2_layout
2 |
3 |
4 | def generate_layout(viz_type, metadata, title=None,
5 | plot_bgcolor='rgba(0,0,0,0)'):
6 |
7 | #### Basic Layout Metadata ####
8 | # Handle title
9 | if type(title) == str:
10 | title = {'text': title, 'x': 0.5}
11 | elif type(title) == dict or title is None:
12 | pass
13 | else:
14 | title = {'text': '**Title Type Error!!!', 'x': 0.5}
15 |
16 | # Handle xaxis
17 | if 'xaxis' in metadata:
18 | xaxis = metadata['xaxis']
19 | else:
20 | xaxis = None
21 |
22 | # Hand yaxis, forcefully add gridcolour to lightgray if not stated
23 | if 'yaxis' in metadata:
24 | yaxis = metadata['yaxis']
25 |
26 | # Check if gridcolor is declared in arguement.json
27 | # but allow pre-declared colour other than lightgry
28 | if 'gridcolor' not in yaxis:
29 | yaxis['gridcolor'] = 'lightgray'
30 | else:
31 | yaxis = {'gridcolor': 'lightgray'}
32 |
33 |
34 | # Only accepting a dictionary or None for legend
35 | if 'legend' in metadata:
36 | legend = metadata['legend']
37 | else:
38 | legend = None
39 |
40 |
41 | # Put all metadata together
42 | layout = {
43 | 'title': title,
44 | 'xaxis': xaxis,
45 | 'yaxis': yaxis,
46 | 'legend': legend,
47 | 'plot_bgcolor': plot_bgcolor
48 | }
49 |
50 | #### Bar Chart Specific Layout ####
51 | if viz_type.lower() == 'bar':
52 | barmode = metadata['viz_subtype']
53 | # barmode = 'simple' is not a option in Plotly, string fixing
54 | layout = barmode_add2_layout(layout, barmode)
55 |
56 | #### Candlestick Specific Layout ####
57 | if viz_type.lower() == 'candlestick':
58 | # If rangeslieder is stated in arguements.json
59 | if 'rangeslider' in metadata:
60 | if layout['xaxis'] is not None:
61 | layout['xaxis']['rangeslider'] = metadata['rangeslider']
62 | else:
63 | layout['xaxis'] = {'rangeslider': metadata['rangeslider']}
64 | # If rangeslieder is not stated in arguements.json
65 | else:
66 | if layout['xaxis'] is not None:
67 | layout['xaxis']['rangeslider'] = {'visible':False}
68 | else:
69 | layout['xaxis'] = {'rangeslider':{'visible':False}}
70 |
71 | #### Bubble Chart Specific Layout
72 | if viz_type.lower() in ['bubblechart', 'bubble_chart'] or (
73 | viz_type.lower() in ['scatter', 'scatterplot', 'scatter_plot']
74 | and metadata['viz_subtype'].lower() in ['bubblechart',
75 | 'bubble_chart']):
76 | if 'constant_itemsizing' in metadata:
77 | if metadata['constant_itemsizing'] in ['t','true','True',True]:
78 | if layout['legend'] is not None:
79 | layout['legend']['itemsizing'] = 'constant'
80 | else:
81 | layout['legend'] = {'itemsizing':'constant'}
82 | else:
83 | if layout['legend'] is not None:
84 | layout['legend']['itemsizing'] = 'constant'
85 | else:
86 | layout['legend'] = {'itemsizing':'constant'}
87 |
88 | #### Histogram Specific Layout
89 | if viz_type.lower() == 'histogram' and (metadata['viz_subtype'].lower() in
90 | ['cate_histogram', 'category_histogram', 'categorical_histogram']):
91 | layout['barmode'] = metadata['barmode']
92 |
93 |
94 | return layout
95 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # Dash Examples
2 |
3 | This is the effort to introduce to use Dash with Python to build dashboard for business intelligence purpose. Please also visit my Medium Post to introduce using Plotly Dash to build a dashboard.
4 |
5 | ## What is Dash?
6 | Dash is an open source Python library to create a web-based visualiztion application provided by Plotly. This package is great for building dashboard, markdown reports and any kinds of data visualization. This package is built on top of pure Plotly and Flask allow you to build a dashboard using pure Plotly library and host the dashboard via Flask. The ideal use of this library could be building a dashboard using Dash and host it on AWS (Or other cloud computers) and allow views to read it via a link.
7 |
8 | ## Good Reasons to build dashboard with Dash
9 |
10 | ### Open Source Tool (It's Free!)
11 | It is free. BI tools like Tableau or Microsoft Power BI are great but they are costly to operate. Dash is a good alternative tool to provide similar quality and experience with no cost.
12 |
13 | ### Run in Python
14 | Dash runs in Python. You may use Pandas and any Python library to manipulate your data frame before render the visualization with Dash.
15 |
16 | ### Great Appearance
17 | The quality of the visualization in Dash or Plotly is very high that is comparable with Tableau charts because Dash renders d3 visualization.
18 |
19 | ### Integrated with Plotly
20 | Plotly is one of the great open source visualization package in the Python library. Many Python developers use Plotly for data visualization. As a product of Plotly, Dash allows developers to integrate their Plotly visualization on the Dash dashboard. Dash is a tool to make building dashboard using Plotly graph easier.
21 |
22 | ### Integrated with Flask
23 | Dash runs web server in Flask. No need to set up in Flask, easy to host the web server in AWS. You don't need to be a web programmer to build the dashboard.
24 |
25 | ### Easy to use
26 | Although the dashboard is viewed in a web broswer, it is a high level tool that the developers are only required to write in Python and have some understanding of html. It means no Javascript or d3 is needed to be written to produce the same product but you may leverage the interactive elements available in d3. Dash is very customizable that you may custom the dashboard using the html layout which eliminates the contraint of pure Plotly's customizability.
27 |
28 | ## Plotly Tutorial
29 | Dash relies on Plotly plots, it is a good idea to understand how Plotly works first. Here are the tutorial and examples for plotting in Plotly:
30 | [Fundamentals](/PlotlyExample)
31 | [Bar Charts](/PlotlyExample/BarChart)
32 | [Line Charts](/PlotlyExample/LineChart)
33 | [Scatter Plot/Bubble Chart](/PlotlyExample/ScatterPlot)
34 | [Box Plots](/PlotlyExample/BoxPlot)
35 | [Pie/Donut Charts](/PlotlyExample/PieChart)
36 | [Histogram](/PlotlyExample/Histogram)
37 | [Treemaps](/PlotlyExample/Treemap)
38 | [Heatmaps](/PlotlyExample/Heatmap)
39 | [Candlestick Charts](/PlotlyExample/CandlestickChart)
40 | [Funnel Chart](/PlotlyExample/FunnelChart)
41 | [Choropleth Graphs](/PlotlyExample/ChoroplethGraph)
42 | [Sunburst Charts](/PlotlyExample/Sunburst)
43 | [Parallel Categories Diagram](/PlotlyExample/ParallelCoordinatesPlot)
44 | [Sankey Diagram](/PlotlyExample/SankeyChart)
45 | [Dendrograms (Decision Tree) (Coming Soon...)](/PlotlyExample/DecisionTree)
46 |
47 | Or click the link here to the [Plotly Example folder](/PlotlyExample) for the selected list of the visualizations can be made with Plotly.
48 |
49 | ## Tutorial and Examples
50 | This repositories contains examples from the official Dash site and myself. There are 3 parts for the tutorial with different levels of functionality.
51 |
52 | [Part 1 - Basics of Using Dash](/Part1)
53 | [Part 2 - Dash Callbacks](/Part2)
54 | [Part 3 - Interactive Visualization](/Part3)
55 | [Dashboard Example - Gaming Console Market Share in 2018](/DashboardExample)
56 |
57 | ## Dockerizing Dash
58 | This section contains the quick-start note for dockerizing Plotly and Dash for your solution. You may find the direction and tips to create Docker Image with Plotly and Dash in the [Dockerize Dash](/DockerizeDash) folder.
59 |
60 | Alternatively, you may read the instructions in this Medium Post: Dockerizing Plotly/Dash
61 |
62 | ## Template Framework for Plotly
63 | You may find the template framework for Plotly when you want to quickly plot something with Plotly. You may find the scripts in the [Template Framework](/PlotlyTemplateFramework) folder.
64 |
65 | ## Template Framework for Dash
66 | There are some template frameworks for Dash when you want to have a prebuilt structure and create a Dash framework right away. You may find the templates in the [](/DashTemplateFramework) folder.
67 |
68 | ## Reference
69 | Official Website of Dash: [Dash User Guide](https://dash.plotly.com/)
70 | Medium Post: [Brief Introduction of Dash](https://medium.com/plotly/introducing-dash-5ecf7191b503) by Plotly
--------------------------------------------------------------------------------