Package: dash-charts
dash_chartsNoteIn 2019-2020, I was building applications with Dash and wanted a way to make them more composable and reusable. Since then, I moved on to other projects and Dash has become far more composable. Dash expanded plotly express and introduced templates along with other changes as the ecosystem has evolved!Given the advances in Dash, I'm going to archive this project, publish a final release to PyPi, and move on to other projectsPython package forPlotly/Dashapps with support for multi-page, modules, and new charts such as Pareto with an Object Orient ApproachIncludes base classes for building a custom chart or application, new charts such as a Pareto, and base classes for tabbed or multi-page applications. See full documentation athttps://kyleking.me/dash_charts/. ( TODO: Currently not online )dash_chartsNov2020-Mar2021 UpdatesQuick Start1. Install2. Example Code3. Resulting Pareto Chart4. Additional NotesDesign PrinciplesLocal DevelopmentExample Charts and TablesPareto ChartGantt ChartTime Vis ChartRolling Mean and STD ChartFitted ChartReal Time SQL DemoCoordinate ChartMarginal ChartData Table ModuleUpload ModuleApplicationsTabbed ApplicationMulti-Page ApplicationPX Generic ApplicationOtherCacheStatic HTML GenerationCoverageExternal LinksInstallationUsageRoadmapContributingLicenseQuick Start1. InstallWith Poetry installdash_chartswith:poetry add dash_charts --git https://github.com/KyleKing/dash_charts.git#main2. Example Code"""Example Dash Application."""fromtypingimportOptionalimportdashfromdashimporthtmlimportplotly.expressaspxfromboximportBoxfromimplementsimportimplementsfromdash_charts.pareto_chartimportParetoChartfromdash_charts.utils_appimportAppBase,AppInterfacefromdash_charts.utils_figimportmin_graph# FIXME: the change to use Box/_ID needs to be implemented in the examples. This is causing failures in the test cases#   Still pending if this is the preferred approach_ID=Box({'chart':'pareto',})"""Default App IDs."""@implements(AppInterface)classParetoDemo(AppBase):"""Example creating a simple Pareto chart."""def__init__(self,app:Optional[dash.Dash]=None)->None:"""Initialize app and initial data members. Should be inherited in child class and called with super().Args:app: Dash instance. If None, will create standalone app. Otherwise, will be part of existing app"""self.name='Car Share Pareto Demo'self.data_raw=Noneself.chart_main=Noneself._id=_IDsuper().__init__(app=app)defgenerate_data(self)->None:"""Format the car share data from plotly express for the Pareto. Called by parent class."""self.data_raw=(px.data.carshare().rename(columns={'peak_hour':'category','car_hours':'value'}))self.data_raw['category']=[f'H:{cat:02}'forcatinself.data_raw['category']]defcreate_elements(self)->None:"""Initialize the charts, tables, and other Dash elements."""self.chart_main=ParetoChart(title='Car Share Pareto',xlabel='Peak Hours',ylabel='Car Hours')defreturn_layout(self)->dict:"""Return Dash application layout.Returns:dict: Dash HTML object"""returnhtml.Div([html.Div([min_graph(id=self._il[self._id.chart],figure=self.chart_main.create_figure(df_raw=self.data_raw),)]),])defcreate_callbacks(self)->None:"""Register the callbacks."""pass# Override base class. Not necessary for this exampleif__name__=='__main__':app=ParetoDemo()app.create()app.run(debug=True)else:app=instance()app.create()FLASK_HANDLE=app.get_server()3. Resulting Pareto Chart4. Additional NotesTO get the most out of the tools, you may want to addcalcipyand add the below snippets to yourpyproject.tomlfile[tool.poetry.dev-dependencies.dash]extras=["testing",]version="*, ^1.19"[tool.poetry.dependencies.calcipy]git="https://github.com/kyleking/calcipy.git"branch="dev/development"rev="01635ea"# Always pin to a commitdevelop=true# Optional: will reinstall each time[tool.poetry.dev-dependencies.calcipy]git="https://github.com/kyleking/calcipy.git"branch="dev/development"extras=["dev","lint","test","commitizen_legacy"]You will also want at minimum thedodo.pyand folder structure fromdash_chartsDesign PrinciplesI wanted to show that an object oriented programming approach to Dash projects could be really powerful for improving code reuse and improving readability in large projects. Below are a couple of design principles to keep that I try to keep in mind when implementing this package.Try to encapsulate all application logic (callbacks, ids, etc.) in application classes or modulesFor components that are reused between application, create amodule. The layout, state, and callbacks can all be delegated to the module rather than cluttering the main application's class and allowing for better code reuseMove any methods that do not require state (self) into standalone functionsIf you can separate Dash (ids/layout/Callbacks) and Plotly (figures/tables) code, you can generate static HTML or PNGs more easily. Sometimes static output is useful when programmatically generating views rather than tweaking the interactive inputs each time.Overall, I find that this package really improves my Dash code and I hope others find it useful. Please feel free to submit PRs or open issues if you have any input. See./DESIGN.mdfor additional information on design decisions and package architectureLocal DevelopmentInitial commands to clone code from Github, create Python virtual environment, and run first example applicationgitclonehttps://github.com/KyleKing/dash_charts.gitcddash_charts
poetryinstall
poetryshell
pythontests/examples/ex_app_px.pyOther useful scripts for testing, documentation, and more:poetryrunptw---m"not INTERACTIVE"poetryrundoitruntestpoetryrundoitExample Charts and TablesBelow are screenshots and links to the example code for each chart or table included in dash_chartsPareto ChartCreate Pareto charts in Dash. Handles ordering the category, calculating the cumulative percentage, and configuring both YAxis.See sample code intests/examples/ex_pareto_chart.py. Screenshot below:Gantt ChartCreate simple Gantt charts in Dash. Doesn't support more advanced features such as dependencies and resource assignment, but effectively shows tasks, progress, and projects in a clear way. You can toggle the different projects on/off and use zoom like a normal Plotly chart.See sample code intests/examples/ex_gantt_chart.py. Screenshot below:Time Vis ChartCreate a TimeVis chart to plot general time visualizations (based ondaattali/timevisfrom R). This chart differs from a Gantt chart by showing events that repeat in the same row.See sample code intests/examples/ex_time_vis_chart.py. Screenshot below:Rolling Mean and STD ChartEasily chart the rolling mean and standard deviation for a given scatter data set. Demonstrates using chart annotations.See sample code intests/examples/ex_rolling_chart.py. Screenshot below:Fitted ChartFit arbitrary scatter data with a specified equation. On hover will show the rounded fit parameters. Useful for experimenting with new data.See sample code intests/examples/ex_fitted_chart.py. Screenshot below:Real Time SQL DemoExample using a Rolling Chart to show real time data from a SQLite database. For the demo, a background thread populates the database as the Dash app runs in a separate thread.See sample code intests/examples/ex_sqlite_realtime.py. Screenshot below:Coordinate ChartChart a discrete data set on a 2D plane with color for intensity. Below examples show how to use theYearGrid(),MonthGrid(), andCircleGrid()classesSee sample code intests/examples/ex_coordinate_chart.py. Screenshot below:Marginal ChartExample creating a new chart from utils_fig.MarginalChartSee sample code intests/examples/ex_marginal_chart.py. Screenshot below:Data Table ModuleDisplay Dash data table from dataframeSee sample code intests/examples/ex_datatable.py. Screenshot below:Upload ModuleUpload module for user-selected CSV, JSON, or SQLite files.See sample code intests/examples/ex_upload.py. Screenshot below:ApplicationsEvery app derives fromAppBase()so that each tab or page can be run independently or part of a more complicated applicationTabbed ApplicationUse theAppWithTabs()base class to quickly build applications with tabbed navigation. You can set tabs to the top/bottom/left/right, to be compact or not, etc.See sample code intests/examples/ex_tabs.py. Screenshot below:Multi-Page ApplicationUse theAppMultiPage()base class to quickly build applications with tabbed navigation. You can set tabs to the top/bottom/left/right, to be compact or not, etc.See sample code intests/examples/ex_multi_page.py. Screenshot below:PX Generic ApplicationTo facilitate general data analysis from a JSON, CSV, or SQLite file, dash_charts includes apps for each px plot type and a tabbed app to bring them all together.See sample code intests/examples/ex_app_px.py. Screenshot below:OtherOther notable components indash_chartsCacheUtilities for utilizing a local cache file system for storing JSON data. Particularly useful if scraping or making many API calls to cache the responses locally.See sample code in the relevant test filetests/test_utils_json_cache.pyStatic HTML Generationutilities for creating static HTML output with all of the CustomCharts above or user-created. Also includes utilities for writing tables, code, markdown, and more to be added.See sample code intests/examples/ex_utils_static.py. Screenshot below:CoverageLatest coverage tableFileStatementsMissingExcludedCoveragedash_charts/__init__.py200100.0%dash_charts/app_px.py13011091.5%dash_charts/components.py1300100.0%dash_charts/coordinate_chart.py1021699.0%dash_charts/custom_colorscales.py300100.0%dash_charts/datatable.py7925068.4%dash_charts/equations.py1100100.0%dash_charts/gantt_chart.py5400100.0%dash_charts/modules_datatable.py10111089.1%dash_charts/modules_upload.py13260054.5%dash_charts/pareto_chart.py4302100.0%dash_charts/scatter_line_charts.py4503100.0%dash_charts/time_vis_chart.py6100100.0%dash_charts/utils_app.py9814685.7%dash_charts/utils_app_modules.py263488.5%dash_charts/utils_app_with_navigation.py1199692.4%dash_charts/utils_callbacks.py346082.4%dash_charts/utils_data.py631098.4%dash_charts/utils_dataset.py7643043.4%dash_charts/utils_fig.py772497.4%dash_charts/utils_helpers.py178752.9%dash_charts/utils_json_cache.py5110080.4%dash_charts/utils_static.py1115095.5%dash_charts/utils_static_toc.py221095.5%Generated on: 2020-11-08T22:46:27.420973External LinksUseful Dash reference linksOfficialDash Docs/Plotly DocsExample AppsPretty annotations fromMarket Ahead, a commercial Dash appPleasant dark app from Dash-Bio,CircosAllDash Sample AppsCode Conceptual inspirationOn Tidy dataUsing field for properties in a @DataClassBest PracticesIBM Design Language (note that v2 doesn't have documentation on visualization yet)ProcessSelect ChartAltChart Decision DiagramPrinciples (color conventions, etc.)Color Library and Data Vis SwatchesInteractionStyleColorsFriendly Guide to ColorsViz-Palette ToolAI Color Palette/CoolorsReferencePandas CheatSheet for Data ManipulationInstallation......echoHelloWorld!...UsageFor more examples, seeScriptsorTestsRoadmapSee theOpen IssuesandMilestonesfor current status and./docs/CODE_TAG_SUMMARY.mdfor annotations in the source code.For release history, see the./docs/CHANGELOG.mdContributingSee the Developer Guide, Contribution Guidelines, etc./docs/DEVELOPER_GUIDE.md./docs/STYLE_GUIDE.md./docs/CONTRIBUTING.md./docs/CODE_OF_CONDUCT.md./docs/SECURITY.mdLicenseLICENSE