(This page has no text content)
CONTENTS IN DETAIL TITLE PAGE COPYRIGHT DEDICATION ABOUT THE AUTHORS ACKNOWLEDGMENTS INTRODUCTION Why This Book Why Plotly Dash Who This Book Is For What’s in the Book Online Resources PART I: CRASH COURSES 1 PYTHON REFRESHER Lists Adding Elements Removing Elements Reversing Lists Sorting Lists Indexing List Elements Slicing Dictionaries List Comprehension Object-Oriented Programming Classes and Objects Terminology Decorator Functions and Annotations Summary 2 PYCHARM TUTORIAL Installing PyCharm Creating a Project Running a Dash App Installing Dash Through PyCharm Using Dash with GitHub Summary
3 A CRASH COURSE IN PANDAS Visual Overview Cheat Sheet Installing pandas Creating Objects in pandas Series DataFrames Selecting Elements in DataFrames Select by Column Select by Index and Slice Select by Label Modifying an Existing DataFrame Summary Resources PART II: BUILDING APPLICATIONS 4 FIRST DASH APP Setting Up the Project Importing the Libraries Data Management Layout and Styling Styling: Embellishing Your App Dash Components HTML Components Core Components Dash Callbacks Callback Decorator Callback Function Callback Diagram Plotly Express Line Charts Summary 5 GLOBAL DATA ANALYSIS: ADVANCED LAYOUTS AND GRAPHS Setting Up the Project Importing the Libraries Data Management Dash Bootstrap Styling Dash Core Components Dash Callbacks Data Retrieval Callback Figure Creation Callback Callback Diagram Callback Ordering Plotly Express Choropleth Maps Summary 6 INVESTMENT PORTFOLIO: BUILDING LARGER APPS Asset Allocation Download and Run the App App Structure Setting Up the Project
Importing the Libraries Adding the Stylesheets Data Management Layout and Styling Components Tabs Card Containers and Sliders Input Containers Tool Tips Data Tables Content Tables Markdown Text Pie Chart Using Plotly Graph Objects Line Chart Using Plotly Graph Objects Dash Callbacks Interactive Figures Callbacks Using State Circular Callbacks and Synchronizing Components Callbacks with Multiple Inputs and Multiple Outputs Summary 7 EXPLORING MACHINE LEARNING Dashboard Apps to Make Machine Learning Models More Intuitive Classification: A Short Guide Support Vector Machines The SVM Explorer App Python Libraries Data Management Layout and Styling Layout Styling Reusable Components Defining a Card Defining a Formatted Slider Defining a Named Slider Defining a Named Dropdown Using a Dash Graph Creating a Plotly Contour Plot Using Dash Loading Dash Callbacks Summary Resources 8 TIPS AND TRICKS Dash Enterprise App Gallery Enhancing Your Learning with the Plotly Forum App Theme Explorer Debugging a Dash App dash-labs Formatting Your Code with Black Follow-up Resources APPENDIX: PYTHON BASICS INDEX
THE BOOK OF DASH Build Dashboards with Python and Plotly by Adam Schroeder, Christian Mayer, and Ann Marie Ward
THE BOOK OF DASH. Copyright © 2022 by Adam Schroeder, Christian Mayer, and Ann Marie Ward. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. First printing 26 25 24 23 22 1 2 3 4 5 ISBN-13: 978-1-7185-0222-2 (print) ISBN-13: 978-1-7185-0223-9 (ebook) Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Rachel Monaghan Production Editor: Jennifer Kepler Developmental Editor: Liz Chadwick Cover Illustrator: Gina Redman Interior Design: Octopod Studios Technical Reviewer: Tom Begley Copyeditor: Audrey Doyle Production Services: Westchester Publishing Services Proofreader: Rachel Head Indexer: BIM Creatives, LLC For information on distribution, bulk sales, corporate sales, or translations, please contact No Starch Press, Inc. directly at info@nostarch.com or: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900 www.nostarch.com Library of Congress Control Number: 2022020454 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
To Isabel, my beloved wife. —Adam
About the Authors Adam Schroeder has been teaching Plotly Dash for over two years on YouTube as @CharmingData. His videos have over 60,000 views per month. Adam is passionate about helping people learn data visualization. He has an MA in government and conflict resolution and works for Plotly. Christian Mayer has a PhD in computer science and is the founder of the popular Python site Finxter.com, an educational platform that helps more than 5 million people a year learn to code. He has published a number of books, including the Coffee Break Python series, and is the author of Python One-Liners (No Starch Press, 2020) and The Art of Clean Code (No Starch Press, 2022). Ann Marie Ward is a Dash contributor and a moderator on the Dash community forum. Ann Marie has a BA in economics and is a retired CEO. She discovered Dash when searching for a better way to analyze financial data and was so amazed by what’s possible to create with Dash that she started to learn Python, JavaScript, and R. Her contributions to Dash include improving documentation, fixing bugs, and adding features. About the Technical Reviewer Tom Begley is a data scientist and the co-creator and maintainer of dash-bootstrap-components. He has a PhD in mathematics and five years of experience working as a data scientist in industry. He discovered Dash when looking for ways to build interactive data visualizations for his clients, and has since become an active contributor to the Dash community and ecosystem.
ACKNOWLEDGMENTS Putting together a programming book like this is a group effort that builds on the ideas and contributions of many people. First and foremost, we want to thank you, the reader, for spending your valuable time with us. Our main goal is to make reading this book worth your while and, hopefully, get you as excited as we are about creating your own dashboard applications. We would also like to thank the Plotly Dash community members for making the Plotly forum a thriving place. Over the years, we’ve learned a lot from the forum and honed our Dash skills thanks to the curiosity and constant support of the community. Our deep gratitude goes to the wonderful team at No Starch Press for making the book writing process such a delightful experience. Special thanks to our outstanding editor, Liz Chadwick, for being there for us throughout the project. Liz truly is a one-of-a-kind editor, and we’re very lucky to have had her support! Jennifer Kepler, our production editor, pushed this book from rough draft to final publication, which was not an easy endeavor—thanks a million, Jennifer! Our technical reviewer, Tom Begley, helped us significantly improve this book by contributing his impressive technical programming and Dash expertise. Moreover, we’re thankful to Bill Pollock, founder of No Starch Press, for believing in our project and allowing us to contribute to his inspiring mission to educate more coders. Lastly, we’re very grateful to our beloved partners for enduring the long night and weekend shifts to work on this project. And with that, let’s get started!
INTRODUCTION Information is power, some say. Data is the new gold, others proclaim. But raw information and data are often meaningless without context. Data is a valuable asset only when properly analyzed, interpreted, and understood. As a result, new fields proliferate. Data scientist, data engineer, data analyst, business intelligence consultant, and machine learning engineer are all increasingly popular careers, and they all share a common role: interpreting data using visual tools such as graphs and dashboards. The goal of this book is to help you create beautiful dashboard apps so that you can visualize your data with just a few lines of code. Whether you’re an aspiring professional, you work with data on a regular basis, or you just love to play with numbers, this book will give you the tools and education to harness the power of data. Why This Book The Plotly Dash framework makes it super easy for you to build your own dashboards. Dashboards are web apps that allow you and your users to dynamically explore data using interactive widgets that receive user input to explain output. For example, they might have sliders, text fields, buttons, and dropdown menus to allow the user to choose what data to show in the resultant charts and graphs, like the maps and bar charts you see in Figure 1. The interactivity of dashboard apps is what has made them increasingly popular in recent years.
Figure 1: Google Analytics dashboard to track website usage Building a Plotly Dash app without proper guidance can be hard. This book will teach you how to create your first interactive, highly visual analytical dashboard apps using practical instructions and easy-to-understand tutorials. It will guide you from absolute Dash beginner to creating your own dashboard apps quickly and confidently. Reading this book will also help you hone crucial 21st-century skills including programming, data analysis, and data science, as well as data visualization and presentation. The community is hungry for stunning data visualizations of dynamic and growing datasets, generated by myriads of data sources such as smart homes, factories, web stores, social networks, video hosting services, and health tracking devices. As the scale and complexity of data proliferate, we’ll see a growing need for dashboard applications that can provide users with a real-time, data-driven overview of what’s happening in the world. Chances are you’ve already used browser-based dashboards in your own life: Google Analytics, Facebook Ad Manager, and Salesforce Dashboards are some examples of real-life dashboard applications. Figure 1 shows a screenshot of the Google Analytics dashboard app that lets you track real-time website traffic. This dashboard shows us that, at the time the screenshot was recorded, most users in the United States and Asia were still sleeping while users in Europe were already busy searching the web. How seamlessly these insights arise when visualizing the data properly using a dashboard app! Creating these types of applications has been possible only for skilled coders and large organizations that were able to connect real-time data sources with dynamic websites to create the unique value proposition provided by dashboard apps. Figure 2 shows a screenshot of the Johns Hopkins dashboard app that visualizes the spread of COVID-19 using fresh and dynamic data streams.
Figure 2: Johns Hopkins dashboard to visualize the spread of a global disease You can view this dashboard live at https://coronavirus.jhu.edu/map.xhtml. The dashboard shows a dynamic counter that tracks the global number of cases, a map that tracks hotspots, figures on the cases per country, a progression of the spread over time, and many more static and dynamic statistics. The dashboard app is able to help hundreds of thousands of people each month get insight from data— insight they would not have obtained using only spreadsheets and tabular data. Figure 3 shows a screenshot of an asset allocation tool created by one of the authors of this book (https://wealthdashboard.app). Figure 3: Wealthdashboard.com app for visualizing your asset allocation This tool allows you to model investment returns by inputting the percentage of your wealth to
allocate to stocks, bonds, and cash and using historical data to visualize key statistics on the return and risk profile of your asset allocation. This is one of the dashboards you will learn to make in this book! The potential uses for dashboard applications are pretty much infinite. For each data source, there’s a useful dashboard application waiting to be created by you. We, the authors, have spent some sleepless nights coding and debugging and figuring out how to make our first Dash apps work. Books on Dash are rare, let alone ones that are also easy to understand and suitable for a Python beginner. So, by starting this project, we decided that it’s time to change that! Check out the many sample apps in the Dash Enterprise App Gallery at https://dash.gallery/Portal for more examples (see Figure 4). Some apps, like the AI Speech Recognition app, are fewer than 100 lines of code! Figure 4: Screenshot of the official Dash Gallery exemplifying the many uses and features of dashboard apps Why Plotly Dash We’ve established that dashboards are great, so let’s look at why you should use Plotly Dash for the job. There are a lot of great alternative frameworks for creating dashboards, including Streamlit, Shiny, Jupyter, Tableau, Infogram, and many more. However, we found a number of compelling reasons to
consider Dash over its competitors in a wide variety of use cases: Dash apps can be written in pure Python, which means if you’re familiar with Python, you’ll be able to get up and running very quickly. It also means it’s easy to integrate data and results from your existing Python work into a Dash app. Python is very expressive and Dash code can be relatively compact, meaning you’re able to prototype and iterate much more quickly, which can be very useful when developing apps to a deadline or in an agile environment where requirements are regularly changing. Dash hides complexity from you, such as communication between the JavaScript frontend and the Python backend. So you don’t need to take on overcomplicated responsibilities such as serialization, deserialization, defining API endpoints, or making HTTP requests. This can significantly reduce boilerplate code. Dash is developed by a Plotly team of people, meaning it has excellent integration with the Plotly graphing library. Plotly and therefore Dash are great choices for making web apps because these interactive graphs are themselves based on web technologies. Dash is built on top of the heavily used Flask framework, giving us many deployment options, ranging from fully managed to self-hosted. Although Dash can only be used with Python, it’s very extensible, allowing you to mix in CSS and JavaScript, and even write your own components using React and the Dash component generator. Although Dash has many advantages, no software is perfect. To help you decide what’s best for you, here are some of Dash’s limitations: Dash has good performance, but if you have a very large number of components, have incredibly complex apps, or are processing huge datasets, you might start to see your app slowing down. Dash is slightly more complicated to get up and running than some no-code or low-code alternatives, and integrations with other enterprise software are not as developed as they are with alternative frameworks; for example, PowerBI has very tight integration with Microsoft enterprise software. While Dash is pure Python, to properly understand what’s going on, you will need to know the basics of HTML and CSS.
Who This Book Is For We wrote this book with the total Dash beginner in mind. Although a little Python background knowledge will help you get the most out of the book, we don’t assume you have a lot of programming experience, so we explain basics such as how to install Dash and related libraries, how to set up your programming environment, and how to use libraries like pandas. An entire course on Python is beyond the scope of this book, but Chapter 1 will go over some of the Python basics that are key to building Dash apps, as well as direct you to resources to help you dig in deeper where you need to. In practice, many readers will already have some experience with the Python programming language. If you know Python but you don’t have experience setting up a programming environment yet, start with Chapter 2. If, on the other hand, you already know Python and you’ve set up your programming environment (preferably PyCharm), you can safely skip to Chapter 3, where we’ll give you a short tutorial on the important pandas library. If you’re an expert coder who knows all those things, just skip all the introductory chapters and start with Chapter 4, where we’ll show you how to create your first Dash app. What’s in the Book This book is set up in two parts: Part I will help you install and set up everything you need to build Dash apps; Part II will have you building four progressively more complex apps, and will wrap up with some general tips. Part I: Crash Courses Chapter 1, Python Refresher, discusses the basics of Python that are most important to building data-based apps, including data types and structures, functions, and even a little on object-oriented programming. Chapter 2, PyCharm Tutorial, guides you through installing the PyCharm coding environment, installing libraries, creating projects, and running your Dash apps. Chapter 3, A Crash Course in pandas, provides you with a visual overview and 10-minute recap of the pandas library for processing tabular data. Part II: Building Applications Chapter 4, First Dash App, shows you how to create your first Dash app using a practical example based on social media analysis. It introduces the building blocks of a Dash app, including the layout and styling sections, Dash components, callbacks, and Plotly Express for making visualizations. After reading this chapter, you’ll know how to create your own basic Dash apps. Chapter 5, Global Data Analysis: Advanced Layouts and Graphs, uses the World Bank global dataset to introduce more components and styling features. This chapter refines and expands upon your basic Dash skills: you’ll interact with an API to retrieve data in real time, and learn to use dash-bootstrap-components to create more sophisticated layouts. Chapter 6, Investment Portfolio: Building Larger Apps, dives even deeper into more advanced Dash components, using a wealth-based dashboard app as an example. You’ll learn how to structure and debug larger Dash apps, use more complex Dash and Bootstrap components, and build your graphs with the lower-level Plotly Graph Objects library. Chapter 7, Exploring Machine Learning, takes you through an app that visualizes machine learning models and gives you background about support vector machines. This shows another
application of Dash: visualizing and exploring how algorithms work. You’ll dig deeper into two numerical libraries often used with Dash: NumPy and scikit-learn. We’ll introduce the contour plot and look at some more complex uses for Dash callbacks. Chapter 8, Tips and Tricks, wraps up the book with the best tips and tricks and some references for further reading on topics including debugging, applying automatic formatting, making use of the Dash community, and exploring yet more apps. Online Resources Throughout the book, we’ll recommend resources made by us, the authors, to augment your learning. There’s only so much you can fit in one book, so to keep this focused, we’ve made plenty of code, videos, and documents available online. Book page with bonus material: https://learnplotlydash.com Adam’s YouTube channel: https://www.youtube.com/c/CharmingData GitHub repository: https://github.com/DashBookProject/Plotly-Dash Updates from the publisher: https://nostarch.com/python-dash Free Python email academy and cheat sheets: https://blog.finxter.com/email-academy
PART I CRASH COURSES Dash builds on Python. While we don’t assume that you are a Python expert by any means, we expect that you have a solid understanding of basic Python concepts and syntax. In this part, we revisit the most relevant Python, PyCharm, and pandas information you need to get the most out of this book. If you find yourself struggling with the code, we’ve added a “Python Basics” appendix to help you improve your Python skills a little bit before reading on. For a more comprehensive introduction, feel free to check out the thorough Python crash courses and cheat sheets provided at the Finxter email academy: https://blog.finxter.com/email-academy. If you feel confident in Python and pandas and have a preferred integrated development environment (IDE) to work with, feel free to jump right into Chapter 4. If you feel you could use a quick revitalization of your Python and pandas skills or would like to set up the same Python IDE that is used throughout the book, keep reading!
1 PYTHON REFRESHER If you’re looking to work on Dash apps, you probably already know at least a little bit of Python. This book doesn’t assume you’re an expert, however, so here we’ll review some important Python concepts that are more relevant to working with Dash, including lists, dictionaries, object-oriented programming, and decorator functions. If you’re already really confident in your abilities in these areas, feel free to skip to Chapter 2, which covers PyCharm, the Python IDE that we’ll use throughout this book. Lists Let’s quickly revise the most important container data type used in practically all Dash apps: Python lists! Lists are important in Dash because they are used to define the layout, they are used to incorporate Dash Bootstrap themes, and they are commonly seen inside the callback and in figures built by Plotly. The list container type stores a sequence of elements. Lists are mutable, meaning you can modify them after they’ve been created. Here we create a list named lst and print its length: lst = [1, 2, 2] print(len(lst)) Our output is simply: 3 We create a list using square brackets and comma-separated elements. Lists can hold arbitrary Python objects, duplicate values, and even other lists, so they are among the most flexible container types in Python. Here we populated our list lst with three integer elements. The len() function returns the number of elements in a list. Adding Elements There are three common ways to add elements to a list that already exists: appending, inserting, and concatenation. The append() method places its argument at the end of the list. Here’s an example of appending: lst = [1, 2, 2]
lst.append(4) print(lst) This will print: [1, 2, 2, 4] The insert() method inserts an element at a given position and moves all subsequent elements to the right. Here’s an example of inserting: lst = [1, 2, 4] lst.insert(2,2) print(lst) This prints the same result: [1, 2, 2, 4] And finally, concatenation: print([1, 2, 2] + [4]) We get: [1, 2, 2, 4] For concatenation, we use the plus (+) operator. This creates a new list by gluing together two existing lists. All operations generate the same list, [1, 2, 2, 4]. The append operation is the fastest because it neither has to traverse the list to insert an element at the correct position as inserting does, nor has to create a new list out of two sublists as concatenation does. To append multiple elements to a given list, use the extend() method: lst = [1, 2] lst.extend([2, 4]) print(lst) The code changes the existing list object lst as follows: [1, 2, 2, 4] The preceding code is an example of a list that’s able to hold duplicate values. Removing Elements We can remove an element x from a list with lst.remove(x), like so: lst = [1, 2, 2, 4] lst.remove(1) print(lst) This gives us the result: [2, 2, 4] This method operates on the list object itself—no new list is created, and the original list is altered. Reversing Lists You can reverse the order of the list elements using the method lst.reverse(): lst = [1, 2, 2, 4] lst.reverse()
print(l) This prints: [4, 2, 2, 1] Reversing the list also modifies the original list object rather than creating a new list object. Sorting Lists You can sort the list elements using the method lst.sort(): lst = [2, 1, 4, 2] lst.sort() print(lst) We see the sorted list: [1, 2, 2, 4] Again, sorting the list modifies the original list object. The resultant list is sorted in ascending order by default. To sort in descending order, you pass reverse=True, as shown here: lst = [2, 1, 4, 2] lst.sort(reverse=True) print(lst) And we see the result is in reverse order: [4, 2, 2, 1] You can also specify a key function and pass it as the parameter key to sort() to customize the sorting behavior. The key function simply transforms one list element into an element that is sortable. For example, it might transform an unsortable object such as a Dash component into a sortable type by using the Dash component’s string identifier as a key. Generally, these key functions allow you to sort lists of custom objects; for example, sorting a list of staff objects by their age. The following example sorts the list but uses the inverse, negative value of an element as a key: lst = [2, 1, 4, 2] lst.sort(key=lambda x: −x) print(lst) This gives us: [4, 2, 2, 1] The key of element 4 is the negative value −4, which is the smallest value among all list elements. Because the list is sorted in ascending manner, this is the first value of the resultant sorted list. Indexing List Elements You can determine the index of a specified list element x using the method list.index(x), like so: print([2, 2, 4].index(2)) print([2, 2, 4].index(2,1)) The method index(x) finds the first occurrence of the element x in the list and returns its index. You can specify a starting index by passing a second argument that sets the index from which to start the search. Consequently, while the first line prints the index of the first occurrence of the value 2, the second line prints the index of the first occurrence of the value 2 but starts the search from index 1. The method immediately finds the value 2 in both cases and prints:
Comments 0
Loading comments...
Reply to Comment
Edit Comment