<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Tate on Medium]]></title>
        <description><![CDATA[Stories by Andrew Tate on Medium]]></description>
        <link>https://medium.com/@ajtate?source=rss-3141101eb522------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*p7KEROyLWflaQmMA.jpg</url>
            <title>Stories by Andrew Tate on Medium</title>
            <link>https://medium.com/@ajtate?source=rss-3141101eb522------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:10:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajtate/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Build a Dashboard in Python — Blog | Hex]]></title>
            <link>https://medium.com/hex-blog/how-to-build-a-dashboard-in-python-blog-hex-71f9085768ef?source=rss-3141101eb522------2</link>
            <guid isPermaLink="false">https://medium.com/p/71f9085768ef</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Andrew Tate]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 20:25:17 GMT</pubDate>
            <atom:updated>2022-11-11T20:25:17.158Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build a Dashboard in Python</h3><p>Imagine you’re a data scientist at a SaaS startup, and your sales team needs a basic dashboard that visualizes pipeline stages and growth. How do you build that in Python?</p><p>Python isn’t short of data visualization options. From the simplicity of Seaborn to the level of control of Matplotlib, if you want a graph, chart, map, table, plot, mesh, or spine, there’s a way to get it with Python. But a dashboard isn’t just data viz. You need to contextualize the data with titles, text, tables, and more plots. And you need to publish it so that people can act on the data and information.</p><p>In this post we are going to take you through <strong>how to set up a basic dashboard with the most common Python tools and libraries</strong>: Matplotlib, Seaborn, and Plotly for visualization, and Flask, Jupyter, Dash, and Hex for deployment.</p><p>Throughout the post, we’ll be plotting a few variations on <a href="https://www.kaggle.com/datasets/gauravduttakiit/sales-pipeline-conversion-at-a-saas-startup">this sales pipeline dataset</a>. Our goal is to visualize the data in a few ways: a bar chart, a line chart, a histogram, and a scatter plot. We’ll also want to give our dashboard users the ability to change the data being displayed and change the data range we’re plotting.</p><p>Let’s go!</p><h3>Building the basic visualizations of a dashboard</h3><p>Matplotlib is the OG of Python data viz. And it looks like it. Modeled on the extortionately-priced but actually-kinda-awesome proprietary <a href="https://www.mathworks.com/products/matlab.html">MATLAB language</a>, Matplotlib puts data in first place and style way back in, like, nineteenth.</p><p>But it is powerful. Let’s plot some of that dataset. This code will give you a basic bar chart that splits deals by won and lost:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%3Fembedded%3Dtrue&amp;display_name=Hex&amp;url=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%2Fe6015aff-e205-408b-9ea6-ed3a5dd1c5d5&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=hex" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2dfce599a65cd614df704e736174633/href">https://medium.com/media/a2dfce599a65cd614df704e736174633/href</a></iframe><p>The bad news is that your sales team is losing a lot of deals.</p><p>The good news is how easy it was to plot that data with Matplotlib. But did we <em>really</em> plot it with Matplotlib? Yes and no. To create the plot we called a built-in Pandas plot() method working on the DataFrame, not a Matplotlib method. But the Pandas plotting methods are provided under the hood by... Matplotlib.</p><p>This is something you’ll see time and again in Python data visualization. Seaborn? Matplotlib under the hood. <a href="https://pypi.org/project/Cartopy/">Cartopy</a>? Matplotlib under the hood. <a href="https://plotnine.readthedocs.io/en/stable/">Plotnine</a>? Matplotlib under the hood. Here’s a<a href="https://matplotlib.org/mpl-third-party/"> list</a> of all the other visualization tools using Matplotlib in some way.</p><p>To produce the same plot in pure Matplotlib, we’d replace:</p><pre>sales_data[&#39;Opportunity Status&#39;].value_counts().plot(<br>   kind=&#39;bar&#39;)</pre><p>with:</p><pre>plt.bar(sales_data[&#39;Opportunity Status&#39;].value_counts().index, sales_data[&#39;Opportunity Status&#39;].value_counts())</pre><p>Note that to use Matplotlib directly, we’re passing our data as an <em>argument</em> to a Matplotlib function, rather than calling a method (.plot) that belongs to our Pandas data.</p><p>There are tons of different ways to “build” these kinds of Matplotlib visualizations, and they come in all shapes and sizes (sorry). Another popular one is using Figure:</p><pre>from matplotlib.figure import Figure<br><br>sales_data = pd.read_csv(&quot;Sales Dataset.csv&quot;)<br><br># Generate the figure **without using pyplot**.<br>fig = Figure()<br>ax = fig.subplots()<br>ax.plot([1, 2])<br>ax.title.set_text(&#39;Won / Lost Opportunities (FY 2019-20)&#39;)<br>ax.set_xlabel(&#39;Opportunity Type&#39;)<br>ax.set_ylabel(&#39;Number of Opportunities&#39;)<br>ax.bar(sales_data[&#39;Opportunity Status&#39;].value_counts().index, sales_data[&#39;Opportunity Status&#39;].value_counts(), color= [&#39;red&#39;,&#39;blue&#39;], alpha = 0.8)<br>fig.savefig(&quot;opportunities_won_lost.png&quot;, format=&quot;png&quot;)</pre><p>For the curious, <a href="https://www.aosabook.org/en/matplotlib.html">Matplotlib’s architecture</a> consists of three layers:</p><ol><li>At the top is the <strong><em>scripting layer</em></strong>. Whenever you use the .plot() method like we did above, you are using the scripting layer. As Matplotlib was built as an open-source version of MATLAB and MATLAB is mostly used by scientists rather than developers, the idea of this scripting layer was to mimic how MATLAB worked and give scientists a less verbose way of creating plots.</li><li>In the middle sits the <strong><em>artist layer</em></strong>. This is where the heavy lifting of Matplotlib is performed. Using this layer you can call each component, or Artist instance, that makes up a plot: the Figure, Axes, Line2D, y-label, xticks… With this layer you can finely control what appears in the final render, which is what we’re doing with the Figure calls above.</li><li>At the bottom is the <strong><em>backend layer</em></strong>. This is the low-level rendering interface that is controlling where pixels go on the screen. The idea here is that this is detached from the higher-level APIs that can then be application-specific. It is this layer that Seaborn, Plotnine, etc. build on.</li></ol><p>For our dashboard, we’ll stick with the Figure method, as using the scripting layer has been known to <a href="https://matplotlib.org/stable/gallery/user_interfaces/web_application_server_sgskip.html">cause memory leaks</a> when used on a server.</p><p>Back to some charts: our sales team wants to understand how quickly opportunities are getting handled (also called <a href="https://blog.hubspot.com/sales/sales-velocity">sales velocity</a>). Let’s build a line chart:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%3Fembedded%3Dtrue&amp;display_name=Hex&amp;url=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%2F9cfcf9ad-07aa-427b-b4e3-10675b2876fc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=hex" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/320b7beae827bcc7241bdd1c4e8c94ba/href">https://medium.com/media/320b7beae827bcc7241bdd1c4e8c94ba/href</a></iframe><p>It looks like the vast majority of opportunities are dealt with in less than 100 days, though there are a few significant outliers.</p><p>This plot won’t be very helpful in a dashboard — it should probably be a histogram. To produce a histogram we only need to change one line:</p><pre>ax.plot(sorted(sales_data[&#39;Sales Velocity&#39;]))</pre><p>Becomes:</p><pre>ax.hist(sales_data[&#39;Sales Velocity&#39;], np.arange(1, 200))</pre><p>(I guess two lines as you probably want to save it with a different filename!)</p><p>Which produces:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%3Fembedded%3Dtrue&amp;display_name=Hex&amp;url=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%2F06d5a6b3-ba0f-4844-9ed0-06686e89315c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=hex" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0f97c2ccb9e3d3cb75d66ffe06019e1/href">https://medium.com/media/f0f97c2ccb9e3d3cb75d66ffe06019e1/href</a></iframe><p>This is much more useful. Now we can see clearly that there is a definite spike in sales velocity of deals around the day 20 mark, and the stark dropoff just before 100 days.</p><p>The same goes for the scatter plot, with the expectation that a) we need another variable, color, to map the color of the points to, and b) we’re going to plot against opportunity size:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%3Fembedded%3Dtrue&amp;display_name=Hex&amp;url=https%3A%2F%2Fapp.hex.tech%2Fhex-public%2Fapp%2Fdec0187f-deb5-4db4-aae5-b6708b59d05f%2F2%2Fd69806c0-0f09-4b88-83e5-4bb3ad3b8869&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=hex" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/95ef7cf1a7139945103bea5fb24ae505/href">https://medium.com/media/95ef7cf1a7139945103bea5fb24ae505/href</a></iframe><p>This is good, but all we have so far is a bunch of individual pngs. For it to be a dashboard, we need to start contextualizing and get it deployed somewhere.</p><h3>Publishing to the web</h3><p><a href="https://flask.palletsprojects.com/en/2.2.x/quickstart/#a-minimal-application">Flask</a> is the simplest way to get your Python code onto the web — it’s a bare bones server that can serve HTTP requests. Flask comes as a Python package like everything else so you can just pip install flask. The &quot;Hello, World&quot; (literally) for Flask is just this:</p><pre>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(&quot;/&quot;)<br>def hello_world():<br>    return &quot;&lt;p&gt;Hello, World!&lt;/p&gt;&quot;</pre><p>Each individual page in your Flask app is defined by a route (this one is just the root directory, /) and a function that returns the HTML for the page. Very simple.</p><p>Save the above file as “hello.py” (not “flask.py”, as this would cause a conflict with Flask internals), run flask --app hello run, and you&#39;ll have a web page that you can easily pop on a server somewhere. Neat.</p><p>The Flask app has two parts: (1) all the logic to manipulate the data and create the charts, and (2) a return HTML to the page. Let’s get our charts in there.</p><p>We’ll start, as always, by importing our libraries:</p><pre>from flask import Flask<br>import pandas as pd<br>from matplotlib.figure import Figure<br>Import numpy as np<br>import base64<br>from io import BytesIO</pre><p>The first three imports you’ve seen before. NumPy is the main data analysis library for Python, for working with numerical data. We are only going to use one method, .arange(), to just output a range of numbers, but NumPy is one of the most powerful libraries you can use with Python.</p><p>Base64 lets us encode binary data as ASCII and BytesIO gives us an in-memory binary stream. We&#39;ll see these in practice in a moment.</p><p>Next, we’ll create an instance of the Flask class, which is the core of the Flask program. It runs the WSGI (web server gateway interface) server that runs your app:</p><pre>app = Flask(__name__)</pre><p>We need to use the route() decorator next. Decorators are a fantastic “syntactic sugar” for Python. When you add a decorator above a function, you add functionality to your function. Here, we add a simple @app.route() decorator that tells Flask knows which route it uses in this function. In this case, the home page:</p><pre>@app.route(&quot;/&quot;)</pre><p>We’re mostly going to copy and paste the code we’ve written for our two charts. But since this code will be running on a server, we need a little middleware to make sure the output of the plots is optimized for web. This is where base64 and BytesIO come in. We create an in-memory buffer with BytesIO and then save our plot in that buffer. We then use base64 to take that binary data and encode it as ASCII so we can render it on the page.</p><p>Let’s remove the def hello_world() and replace it with this def dashboard() function:</p><pre>def dashboard():<br>   sales_data = pd.read_csv(&quot;Sales Dataset.csv&quot;)<br><br>   # Generate the figure for the Won / Lost Opportunities.<br>   fig = Figure()<br>   ax = fig.subplots()<br>   ax.plot([1, 2])<br>   ax.title.set_text(&#39;Won / Lost Opportunities (FY 2019-20)&#39;)<br>   ax.set_xlabel(&#39;Opportunity Type&#39;)<br>   ax.set_ylabel(&#39;Opportunities&#39;)<br>   ax.bar(sales_data[&#39;Opportunity Status&#39;].value_counts().index,<br>          sales_data[&#39;Opportunity Status&#39;].value_counts(), color=[&#39;red&#39;, &#39;blue&#39;], alpha=0.8)<br>   bar_buf = BytesIO()<br>   fig.savefig(bar_buf, format=&quot;png&quot;)<br>   bar_data = base64.b64encode(bar_buf.getbuffer()).decode(&quot;ascii&quot;)<br><br>   # Generate the histogram for Sales Velocity.<br>   fig = Figure()<br>   ax = fig.subplots()<br>   ax.plot([1, 2])<br>   ax.title.set_text(&#39;Sales Velocity (FY 2019-20)&#39;)<br>   ax.set_ylabel(&#39;Opportunities&#39;)<br>   ax.set_xlabel(&#39;Days&#39;)<br>   ax.hist(sales_data[&#39;Sales Velocity&#39;], np.arange(1, 200))<br>   fig.savefig(&quot;velocity_histogram.png&quot;, format=&quot;png&quot;)<br>   hist_buf = BytesIO()<br>   fig.savefig(hist_buf, format=&quot;png&quot;)<br>   hist_data = base64.b64encode(hist_buf.getbuffer()).decode(&quot;ascii&quot;)<br><br>   # Generate the scatter plot for Sales Velocity.<br>   fig = Figure()<br>   ax = fig.subplots()<br>   ax.plot([1, 2])<br>   ax.title.set_text(&#39;Sales Velocity (FY 2019-20)&#39;)<br>   ax.set_ylabel(&#39;Opportunity Size (USD)&#39;)<br>   ax.set_xlabel(&#39;Days&#39;)<br>   colors = {&#39;Won&#39;: &#39;blue&#39;, &#39;Loss&#39;: &#39;orange&#39;}<br>   ax.scatter(sales_data[&#39;Sales Velocity&#39;], sales_data[&#39;Opportunity Size (USD)&#39;],<br>              c=sales_data[&#39;Opportunity Status&#39;].map(colors))<br>   scatter_buf = BytesIO()<br>   fig.savefig(scatter_buf, format=&quot;png&quot;)<br>   scatter_data = base64.b64encode(scatter_buf.getbuffer()).decode(&quot;ascii&quot;)</pre><p>The last thing we need to do is return each chart data within its own html &lt;img&gt; tag to render it to the browser:</p><pre>return f&quot;&quot;&quot;&lt;img src=&quot;data:image/png;base64,{bar_data}&quot; /&gt;<br>           &lt;img src=&quot;data:image/png;base64,{hist_data}&quot; /&gt;<br>           &lt;img src=&quot;data:image/png;base64,{scatter_data}&quot; /&gt;&quot;&quot;&quot;</pre><p>And you have the foundation of a decent dashboard!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b7kOmUX7buebrczy.png" /></figure><p>Now that we have some starting plots, we need to help the viewer understand what they are about.</p><h3>Adding contextual information</h3><p>At the moment we have some charts on a page. We want to add a title, some text, and a table of some of the data.</p><p>We can do all of these using Flask, with just a few changes to the code above. The main change is that instead of returning image elements (plus now all the text and table as well), we’re going to create a template for all this using <a href="https://palletsprojects.com/p/jinja/">jinja2</a>. Jinja is a templating engine that allows you to pass variables into html. Create a /templates directory in the same directory as your Flask app, then add a dashboard.html file in that directory containingsome basic jinja code:</p><pre>&lt;html&gt;<br> &lt;body&gt;<br>   &lt;h1&gt;{{page_title}}&lt;/h1&gt;<br>   &lt;p&gt;{{introductory_text}}&lt;/p&gt;<br>   &lt;div&gt;{{ table | safe }}&lt;/div&gt;<br>   &lt;p&gt;{{bar_text}}&lt;/p&gt;<br>   &lt;div&gt;<br>     &lt;img src=&quot;data:image/png;base64,{{ bar_data }}&quot; /&gt;<br>   &lt;/div&gt;<br>   &lt;p&gt;{{hist_text}}&lt;/p&gt;<br>   &lt;div&gt;<br>     &lt;img src=&quot;data:image/png;base64,{{ hist_data }}&quot; /&gt;<br>   &lt;/div&gt;<br>   &lt;p&gt;{{scatter_text}}&lt;/p&gt;<br>   &lt;div&gt;<br>     &lt;img src=&quot;data:image/png;base64,{{ scatter_data }}&quot; /&gt;<br>   &lt;/div&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Back in our “hello.py” file, those five text variables are declared exactly how you would normally in Python:</p><pre>page_title = &quot;Sales Dashboard&quot;<br>introductory_text = &quot;During Fiscal Year 2019-2020, we&#39;ve collected 13 metrics from on 78,025 opportunities to help understand the effectiveness of the sales team in the company. Here is a quick example of the data we have analyzed:&quot;<br>bar_text = &quot;So we are looking at the size of the opportunity, data about the prospect (revenue, team size, location), what product they are interested in, the sales channel they&#39;ve come through, the sales velocity, and whether the opportunity ended up Won or Lost. Here is a bar chart showing the number of won and lost opportunities:&quot;<br>hist_text = &quot;We also took a look at sales velocity to understand how quickly these deals were moving through the pipeline. Here is a histogram of sales velocity vs opportunities:&quot;<br>scatter_text = &quot;We also expanded out this type of analysis across all sales velocity lengths to see if there was any pattern to length of sales process, opportunity size, and whether the deal was closed won or lost:&quot;</pre><p>So we have a page title, an initial text paragraph, then a table. To create a table from the first N rows of our data, we can use .to_html():</p><pre>table = sales_data.to_html(index=False, max_rows=10)</pre><p>We can then return all of this using the render_template() method in <a href="https://flask.palletsprojects.com/en/2.2.x/quickstart/#rendering-templates">Flask</a> with the name of our template file (&#39;dashboard.html&#39;):</p><pre>return render_template(<br>    &quot;dashboard.html&quot;,<br>    bar_data=bar_data,<br>    hist_data=hist_data,<br>    scatter_data=scatter_data,<br>    page_title=page_title,<br>    introductory_text=introductory_text,<br>    bar_text=bar_text,<br>    hist_text=hist_text,<br>    scatter_text=scatter_text, <br>    table=table)</pre><p>With all that code, you’ll end up with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ikPeQ7CzDc5VwjT6.png" /></figure><p>OK, so it does look like a dashboard from 1993. But it is a dashboard, and one built entirely in Python, using just built-in methods, Pandas, Matplotlib, and Flask. It’s running locally right now, but it would be no sweat to get this up on a server and make it accessible to your broader team.</p><p><strong>Next steps for this dashboard</strong></p><p>At this point, there are a few more things we’d want to do to move this into a more production-ready state:</p><ol><li><strong>Add some styling</strong>. Flask outputs html, so you can style all this output through CSS. Now that we are using a template, we can also pull in a css file in the head of the template and add classes to each element.</li><li><strong>Deploy it.</strong> Currently, this is just on localhost. If you want your team (or the waiting world) to see it, it has to be deployed to the web. The easiest way to do that for Flask is something like<a href="https://realpython.com/flask-by-example-part-1-project-setup/"> Heroku</a> or<a href="https://fly.io/docs/languages-and-frameworks/python/"> fly.io</a>.</li><li><strong>Connect to a database</strong>. In a production environment, it’s more likely that data for a dashboard is going to come from a database, rather than from a csv. Piping data from a db into Python is easy as long as you have the right library and you can even<a href="https://hex.tech/blog/how-to-write-sql-in-pandas/"> write sql in Python with Pandas</a> directly to query your data.</li></ol><p>Using Matplotlib and Flask like this is the lowest level and trickiest way to build a dashboard in Python. It gives you maximal control but maximal headaches. So if you have <em>very</em> specific customizability needs, need to make several external API calls, or are already committed to Flask, this is probably the right option for you. If not, you should definitely read on.</p><h3>Adding interactivity to our dashboard with Dash</h3><p>You can, with some magic (and several hundred StackOverflow searches), make that Flask dashboard interactive with Matplotlib. But purpose-built Python tools like <a href="https://plotly.com/dash/">Dash</a>, <a href="https://streamlit.io/">Streamlit</a>, and <a href="https://hex.tech/">Hex</a> will make this much easier. Frameworks built for dashboarding give you control over your data and charting of regular libraries but remove (most) of the headache of adding interactivity and pushing those dashboards to production.</p><p>Let’s start with Dash. Dash is basically a pro version of what we built initially. How do you get it up and running? Lo and behold, you pip install dash.</p><p>Here are the imports we’ll need:</p><pre>from dash import Dash, html, dcc, Input, Output, dash_table<br>import plotly.express as px<br>import pandas as pd</pre><p>These functions from Dash that will help us with adding plots, text, and interactivity to our dashboard. plotly is the visualization library we&#39;ll be using here ( <a href="https://plotly.com/">plotly</a> built Dash). You can use plotly entirely independently of Dash, and, as we&#39;ll see, it is extremely similar to Matplotlib.</p><p>Next create an instance of the Dash class:</p><pre>app = Dash(__name__)</pre><p>You can see how similar this is to Flask-in fact, it is Flask under the hood.</p><p>Plotting basic charts is pretty much the same as with Flask, except we use px.bar(), px.line(), px.histogram(), and px.scatter.</p><p>Instead of rendering everything to a template, we build the html within our app.py file using the helpers we imported. To create the initial text, table, and first graph:</p><pre>sales_data = pd.read_csv(&#39;Sales Dataset.csv&#39;)<br>sales_data_table = sales_data.head(10)<br><br>sales_bar = px.bar(sales_data, x=sales_data[&#39;Opportunity Status&#39;].value_counts().index, y=sales_data[&#39;Opportunity Status&#39;].value_counts(<br>), color=[&#39;red&#39;, &#39;blue&#39;])<br><br>app.layout = html.Div(children=[<br>   html.H1(children=&#39;Sales Dashboard&#39;),<br><br>   html.Div(children=&#39;&#39;&#39;During Fiscal Year 2019-2020, we&#39;ve collected 13 metrics from on 78,025 opportunities to help understand the effectiveness of the sales team in the company. Here is a quick example of the data we have analyzed:<br>   &#39;&#39;&#39;),<br><br>   html.H4(&#39;Data table&#39;),<br>   html.P(id=&#39;table_out&#39;),<br>   dash_table.DataTable(<br>       id=&#39;table&#39;,<br>       columns=[{&quot;name&quot;: i, &quot;id&quot;: i}<br>                for i in sales_data_table.columns],<br>       data=sales_data_table.to_dict(&#39;records&#39;),<br>       style_cell=dict(textAlign=&#39;left&#39;),<br>       style_header=dict(backgroundColor=&quot;paleturquoise&quot;),<br>       style_data=dict(backgroundColor=&quot;lavender&quot;)<br>   ),<br><br>   html.Div(children=&#39;&#39;&#39;<br>       So we are looking at the size of the opportunity, data about the prospect (revenue, team size, location), what product they are interested in, the sales channel they&#39;ve come through, the sales velocity, and whether the opportunity ended up Won or Lost. Here is a bar chart showing the number of won and lost opportunities:<br>   &#39;&#39;&#39;),<br><br>   dcc.Graph(<br>       id=&#39;sales-bar&#39;,<br>       figure=sales_bar<br>   ),<br>])</pre><p>The html components create the basic html elements for the page, dash_table creates the table, and dcc.Graph creates the plots. Then, a simple python [filename].py runs the server.</p><p>Here is what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7QgVRUt283e_sSad.png" /></figure><p>That table is interactive. When you click on a cell, you can display its data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Z-H9xy-A9Z1_slNP.gif" /></figure><p>You do this in Dash with callbacks. These are simple functions that manipulate the html rendered. Here is the callback function for that table:</p><pre>@app.callback(<br>   Output(&#39;table_out&#39;, &#39;children&#39;),<br>   Input(&#39;table&#39;, &#39;active_cell&#39;))<br>def update_graphs(active_cell):<br>   if active_cell:<br>       cell_data = sales_data_table.iloc[active_cell[&#39;row&#39;]<br>                                         ][active_cell[&#39;column_id&#39;]]<br>       return f&quot;{active_cell[&#39;column_id&#39;]}: {cell_data}&quot;<br>   return &quot;Select a cell to see its data here&quot;</pre><p>The @app.callback is a decorator for callbacks. Output() and Input() are Dash functions that let you select what the input and output of the callback are, and then you can write a simple function that updates the text.</p><p>But we want more than just the table to be interactive-we want the charts to be interactive as well. In our Flask deployment, the scatter plot is <em>busy</em>. We can add a slider to narrow down the amount of data we show in the window:</p><pre>px.scatter(<br>       sales_data, x=&quot;Sales Velocity&quot;, y=&quot;Opportunity Size (USD)&quot;,<br>       color=&quot;Opportunity Status&quot;, hover_data=[&#39;Opportunity ID&#39;])</pre><p>This would plot sales velocity against opportunity size, with the color of each data point decided by the opportunity status (Won/Loss). Plotly plots have some built in interactivity, so you can hover over each data point and see information about the opportunity.</p><p>But we can wrap this inside a callback to add further functionality. Say we wanted to inspect sales velocity a bit and narrow down opportunities to certain velocities. Creating the html is much like above:</p><pre>app.layout = html.Div([<br>   html.H4(&#39;Sales velocity&#39;),<br>   dcc.Graph(id=&quot;scatter-plot&quot;),<br>   html.P(&quot;Filter by Sales Velocity:&quot;),<br>   dcc.RangeSlider(<br>       id=&#39;range-slider&#39;,<br>       min=0, max=200, step=1,<br>       marks={0: &#39;0&#39;, 200: &#39;200&#39;},<br>       value=[0, 20]<br>   ),<br>])</pre><p>Only here we have also added a RangeSlider so we can control the range of our sales velocity selection. The callback is:</p><pre>@app.callback(<br>   Output(&quot;scatter-plot&quot;, &quot;figure&quot;),<br>   Input(&quot;range-slider&quot;, &quot;value&quot;))<br>def update_bar_chart(slider_range):<br>   sales_data = pd.read_csv(&#39;Sales Dataset.csv&#39;)<br><br>   low, high = slider_range<br>   mask = (sales_data[&#39;Sales Velocity&#39;] &gt; low) &amp; (<br>       sales_data[&#39;Sales Velocity&#39;] &lt; high)<br>   fig = px.scatter(<br>       sales_data[mask], x=&quot;Sales Velocity&quot;, y=&quot;Opportunity Size (USD)&quot;,<br>       color=&quot;B2B Sales Medium&quot;, size=&quot;Sales Stage Iterations&quot;, hover_data=[&#39;Opportunity ID&#39;])</pre><p>The input to the callback is the range slider and the output is the plot itself. We can then create a mask that will be just our data selection depending on where the slider is. All we have to do is pass that mask into the DataFrame in the scatter plot and it will only plot that specific data. Here’s what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*7VultTJEdiupe8f5.gif" /></figure><p>When we put all this together, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OsCh0C8dxSTvhvO2.png" /></figure><p>Like the Matplotlib/Flask option, this is missing styling, but you can add it via a CSS file as you are outputting HTML. You can deploy this via Heroku/Fly.io, or use the <a href="https://plotly.com/">Dash Enterprise platform</a>.</p><h3>A couple of other ways to build a dashboard</h3><p>Because this is Python, there aren’t just two ways of doing this, there are probably 200. Here’s a couple of other ways to get a dashboard up and running quickly.</p><h3>Creating a dashboard from a notebook</h3><p>You’re probably already familiar with <a href="https://hex.tech/blog/beginners-guide-to-python-notebooks/">Jupyter Notebooks</a>. All of the code above will work in a Jupyter notebook. We’ve put together a full .ipynb notebook <a href="https://github.com/ajtatey/jupyter-sales-dashboard/blob/main/Sales%20Dashboard.ipynb">here</a>.</p><p>You can then turn that report into a dashboard with<a href="https://voila.readthedocs.io/en/stable/"> Voila</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YSyGNGTc1jW_npJR.png" /></figure><p>Now we’re dashboarding. It’s not perfect, but the text and data is clearer. If you are already using notebooks, this is a great option. If you need your dashboard to be seen wider, you can publish Voila notebooks using <a href="https://mybinder.org/">Binder</a>.</p><h3>Creating a Python dashboard in the cloud</h3><p>A cloud notebook like <a href="https://hex.tech/">Hex</a> means you can completely remove all the manual set up-the dashboard will be available to share with your team by default.</p><p>As <a href="https://hex.tech/blog/data-notebooks-for-cloud-era/">it’s a notebook</a>, all the plotting and text work the same as in Jupyter. In fact, I can just directly upload my .ipynb file and the dataset and have the notebook ready to go.</p><p>Here we’ve also added a Hex <a href="https://learn.hex.tech/docs/logic-cell-types/display-cells/chart-cells">chart cell</a> at the end for some interactivity:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fapp.hex.tech%2F1f958060-0053-4da2-a34b-24e8eca8e84d%2Fapp%2F1bfd41d2-cf68-4cd3-a81f-dedc93061734%2F1%3Fembedded%3Dtrue&amp;display_name=Hex&amp;url=https%3A%2F%2Fapp.hex.tech%2F1f958060-0053-4da2-a34b-24e8eca8e84d%2Fapp%2F1bfd41d2-cf68-4cd3-a81f-dedc93061734%2F1%2Fec762ca3-1326-4f08-8f6d-f1390cc15915&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=hex" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec8836046139104ba3116adf6424553e/href">https://medium.com/media/ec8836046139104ba3116adf6424553e/href</a></iframe><h3>Choosing the right Python dashboard</h3><p>You have a ton of options when you are creating a dashboard with Python, both in terms of the data viz libraries you use, but also in the way you can deploy them.</p><ul><li>If you want to do everything from scratch (or it’s just for you), Matplotlib and Flask work.</li><li>If you want a professional dashboard for sharing widely, Dash works.</li><li>If you are already familiar with notebooks and use them for analysis, Voila works.</li><li>If you need to get something shared with your team quickly, Hex works.</li></ul><p>The power of Python is that you can use any and all visualization with any of these methods. You can mix and match to show your data the best. All of this is Python, so it all works well together. Don’t feel constrained to just one way of doing dashboarding-experiment and play until you get the best solution for your data.</p><p><em>Originally published at </em><a href="https://hex.tech/blog/how-to-build-a-dashboard-in-python/"><em>https://hex.tech</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f9085768ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hex-blog/how-to-build-a-dashboard-in-python-blog-hex-71f9085768ef">How to Build a Dashboard in Python — Blog | Hex</a> was originally published in <a href="https://medium.com/hex-blog">The Hex Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginner’s guide to Python notebooks — Blog | Hex]]></title>
            <link>https://medium.com/hex-blog/a-beginners-guide-to-python-notebooks-blog-hex-c7f041b59b10?source=rss-3141101eb522------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7f041b59b10</guid>
            <dc:creator><![CDATA[Andrew Tate]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 17:43:08 GMT</pubDate>
            <atom:updated>2022-11-11T20:26:40.999Z</atom:updated>
            <content:encoded><![CDATA[<h3>A beginner’s guide to Python notebooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkrHlWhEhGQyuZW2aSa_8w.png" /></figure><blockquote><em>“When I started working on IPython I told myself and my adviser that this was just going to be an afternoon hack and that I would get back to ‘real work’ very soon.” ( </em><a href="https://web.archive.org/web/20170720121512/http://www.nature.com/naturejobs/science/articles/10.1038/nj7493-523a"><em>source</em></a><em>)</em></blockquote><p>So said <a href="https://twitter.com/fperez_org">Fernando Perez</a>, the inventor of IPython and its successor Jupyter, in the final year of his PhD in theoretical physics at the University of Colorado, Boulder.</p><p>21 years later, that ‘afternoon hack’ is part of hundreds of thousands of data workflows, and forms the core of data analysis at companies like Netflix, Lyft, PayPal, and Bloomberg. But if you are used to hacking together Python scripts for your data analysis, then notebooks can look… odd. You code in the browser, you run it line by line, and why do you have to work with a colonel?</p><p>Once you get over the oddness, you can start to see what companies like Netflix see. Notebooks let you pull apart your code so you can see the data at every stage, examine and explore it, and then put it all back together again to present a full story.</p><p>In this post we’ll explain what data notebooks are, why we think they are important, and take you through the first stages of creating and using your own. Here’s what we’ll cover:</p><ol><li>Why data teams use notebooks, and why you should too</li><li>Getting a notebook up and running<br> a. The cell<br> b. The kernel<br> c. Architecture and security<br> d. Installation options and distribution</li><li>Running your first code</li><li>Doing something useful with your notebook</li><li>Going deeper on data notebooks</li></ol><h3>Why data teams use notebooks, and why you should too</h3><p>“ <a href="https://netflixtechblog.com/notebook-innovation-591ee3221233">run code, explore data, present results</a>.”</p><p>This is the fundamental pattern of data analytics. Run some code, see what the data says, code, explore, code, explore, code, explore until you get something you can show to your team or the world (or not).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxOIL0eGsk_TsCCgcyoxHw.png" /></figure><p>This is what Perez built his initial IPython notebooks for-making his own analysis easier. He wanted to take everything you do in a data exploratory pipeline and bundle it into a single document: the notebook.</p><p>Here’s what a published notebook can look like, taken from the <a href="https://hex.tech/gallery/churn-monitor">Hex notebook gallery</a>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fapp.hex.tech%2Fatreides%2Fapp%2F2a117a19-f6d0-4e3a-b320-200ebc669042%2Flatest%3Fembedded%3Dtrue&amp;display_name=Hex&amp;url=https%3A%2F%2Fapp.hex.tech%2Fatreides%2Fapp%2F2a117a19-f6d0-4e3a-b320-200ebc669042%2Flatest&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=hex" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/887217cc4b36f4f310f998b844e3372c/href">https://medium.com/media/887217cc4b36f4f310f998b844e3372c/href</a></iframe><p>Notebooks are designed for this loop:</p><ul><li><strong>Run code</strong>: A notebook runs Python code in the same way any .py file you write does; you can use all the same libraries, etc. in the same way a regular Python environment does.</li><li><strong>Explore data</strong>: In a notebook, you run lines of code in isolated cells. This makes it easier to see the output of <em>just</em> those lines. The outputs are presented inside the document instead of in a terminal, making it easier to see what’s happening with your data as you analyze. It’s iterative!</li><li><strong>Present results</strong>: You can incorporate visuals from the data outputs — like tables and charts — directly in the document, alongside text and other images to present your analysis as a single entity. You can then export the document in different formats with different styling. Much easier than telling your teammate to run a .py file in their terminal.</li></ul><p>This all makes notebooks great for playing with your data. As you’ll see as we go through a couple of examples, you can stop the code at any point to take a look at the output, then go back and continually adjust your code until you get what you want. You don’t have to wait for all the analysis to happen-you can take it step-by-step.</p><p>Weirdly, this benefit of notebooks can also be a limitation. Analysts have primarily used notebooks for ad-hoc, small analyses. They explore the data and build a pipeline/model/workflow in a notebook, but then port it over to regular files (i.e. productionize it) when they need to schedule or scale the analysis or model.</p><p>But that is changing. Notebooks are critical parts of the data pipeline for major companies:</p><ul><li>At<a href="https://netflixtechblog.com/notebook-innovation-591ee3221233"> Netflix</a>, most data access goes through a notebook rather than direct access through an API. They use them for scheduled tasks and have a set of templates to run specific analyses.</li><li>At<a href="https://mingze-gao.com/posts/bloomberg-bquant/#some-quick-examples"> Bloomberg</a>, they have experimented with notebooks embedded in the Bloomberg terminal so analysts can access data and test trading strategies directly in the terminal.</li><li>At<a href="https://conferences.oreilly.com/jupyter/jup-ny/public/schedule/detail/68405.html"> PayPal</a>, they deploy Jupyter as a platform and have developed their own extensions to work specifically with PayPal data.</li><li>At<a href="https://eng.lyft.com/lyftlearn-ml-model-training-infrastructure-built-on-kubernetes-aef8218842bb"> Lyft</a>, they built LyftLearn, which uses Jupyter notebooks within Kubernetes containers to develop their ML models.</li></ul><p>But we’re going to start simpler. Though notebooks at these companies are becoming sophisticated data tools, at their heart they are still just about “ <em>run code, explore data, present results</em>.” That is what we want to show you how to do here. Let’s get going.</p><h3>Getting a notebook up and running</h3><p>It’s very easy, assuming that you’ve already got a Python environment installed and working. Install Jupyter by opening a new terminal and running:</p><pre>pip install jupyter</pre><p>Once you’ve got Jupyter installed, you can run it with:</p><pre>jupyter notebook</pre><p>There you go. A new browser window or tab should load <a href="http://localhost:8888/">http://localhost:8888/</a> and you are now up and running with a Python notebook. Perez’s afternoon hack in all its glory.</p><p>Let’s look at the interface and go through a few core ideas in notebooks before we launch into any code. The first page you’ll see is the directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0t8qkHKGsRN1julH6MUUmA.png" /></figure><p>Here we see what is in the directory where we launched Jupyter. In this case an env directory (always <a href="https://www.google.com/url?q=https://docs.python.org/3/library/venv.html&amp;sa=D&amp;source=docs&amp;ust=1663090276494252&amp;usg=AOvVaw1lJZdXeSA98IOB9urdIKBC">venv</a>, people) and nothing else. To generate your first notebook, click on ‘New’ and select ‘Python 3 (ipykernel).’</p><p>This will create a file called <em>Untitled.ipynb</em>. (Congratulations, you’ve just created the first of your many hundreds of “Untitled.ipynb” files. <a href="https://xkcd.com/1459/">Obligatory xkcd</a>). .ipynb stands for IPython Notebook, and this is your actual notebook file.</p><p>Click on it and it’ll open up to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLWikSyGjiez1OVWw_wmNw.png" /></figure><p>This is where you do your work in a notebook. All the code you’d normally put in a .py file will go here instead.</p><h3>The cell</h3><p>The most obvious part of this page is the <strong>cell</strong>. This is where you type all your code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymJvYb0Vq3qgBAuT84eYxg.png" /></figure><p>You type your code in there as you would in a .py file. The difference is that you don’t type all your code in a single cell. You write a single statement or small group of statements per cell and then execute just that code. Your entire notebook is made up of a sequence of these cells, building your analysis as you go. We’ll see how this works in practice in a minute.</p><p>Let’s talk about two other parts of this page, which are vital to understanding how notebooks operate. Up in the top-right corner you’ll see a kernel indicator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*DVnj-g8of_t1M0FW-Dnscg.png" /></figure><h3>The kernel</h3><p>“Python3 (ipykernel)” means this notebook is running (or going to run) the IPython kernel.</p><p>The <strong>kernel</strong> is the heart of a notebook. It is the process that is running your code. For most of the work you will do with a Python notebook, this is the IPython kernel. But, and this is the clever part, it doesn’t have to be. You can change the kernel your notebook is running to, get this, <em>any other language</em>. 🤯</p><p>Want to run R code? Use the<a href="http://irkernel.github.io/"> IRKernel</a>. Want to run Go? Use<a href="https://github.com/takluyver/igo"> IGo</a>. Want to go oldskool with some Fortran? You’ve got options with either<a href="https://github.com/sourceryinstitute/jupyter-CAF-kernel"> Coarray-Fortran</a> or<a href="https://lfortran.org/"> LFortran</a>. Whatever the flavor of your language, there is a<a href="https://github.com/jupyter/jupyter/wiki/Jupyter-kernels"> kernel for you</a>. You can even use an <a href="https://vatlab.github.io/sos-docs/doc/user_guide/multi_kernel_notebook.html">extension</a> to mix multiple kernels within the same notebook.</p><p>This is why notebooks are no longer called <em>IPython</em> notebooks- IPython is now just the name of a single kernel available to you. They are now <em>Jupyter</em> notebooks because the ‘notebook’ part is language-agnostic. You can run whatever kernel you need that gets you the analysis you want. Think of a notebook as a particular way of interfacing with a programming language; the language itself can be pretty much anything.</p><h3>Architecture and security</h3><p>The second part to take note of is the ‘Trusted’ flag. As you’ll have noticed, given that you are working on ‘localhost’ and in a browser, when you run a Jupyter notebook, you start a <strong>server</strong>.</p><p>Here is the full <a href="https://docs.jupyter.org/en/latest/projects/architecture/content-architecture.html">architecture</a> of the notebook you just started:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YaDqJJOUjpnGagpVS5GRA.png" /></figure><p>You code in the browser, the browser interacts with the server through websockets, and then the server interacts with the kernel through a message queue (and also writes to the notebook file).</p><p>It says ‘Trusted’ because it can also say ‘Not Trusted’ if you open up a file you didn’t write. Servers mean code execution, and as we’ve just seen, a huge benefit of Jupyter notebooks is that they can execute almost any code. Excellent if you wrote that code, not so great if you don’t know where that code came from.</p><p>If you were allowed to execute any code on this server, you would be opening up yourself to a world of pain. A malicious actor could send you a notebook file that you run which outputs JavaScript, which does unspeakable things.</p><h3>Installation options and distributions</h3><p>We’ll be using the pip install method throughout this article, but there are other options for starting a notebook.</p><p>The first is another way to get it up and running on your computer: <a href="https://www.anaconda.com/">Anaconda</a>. Anaconda is a full ‘data science platform.’ It won’t just install Jupyter, it’ll also install all the other libraries you need for data science: pandas, numpy, scipy, matplotlib. Like 100 different libraries. This is good if you are going to be using all these libraries, but the pip way lets you have finer control over your dev environment.</p><p>The second way is to use an online notebook. This might be a cloud notebook like <a href="https://hex.tech/">Hex</a> if you are trying to connect to data in a selection of data warehouses. Or it might be an online version of Jupyter like <a href="https://jupyter.org/try-jupyter/lab/">JupyterLab</a> or <a href="https://hub.gke2.mybinder.org/user/voila-dashboards-voila-8tiwq0bw/voila/tree/notebooks?token=c7XqWrHbQZKVPQpsy2cQSw">Voila</a>. Both are going to work the same way (give or take some debugging) as a local version, with all the libraries preinstalled on the server.</p><p>Online notebooks tend to be better for collaborating and sharing. For instance, here is a notebook you can run to play around with the latest image-generating AI: <a href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/stable_diffusion.ipynb">Stable Diffusion</a>.</p><p>Sharing and collaborating is a well documented weakness of notebooks. You have to share the document and collaborate back and forth, which feels like you’re doing data science for the Pyramids. Developers today expect much better collaborative tooling. These issues, along with code versioning, are being resolved by online notebooks that are designed with collaboration in mind, taking lessons from developer workflows and moving them into data analysis.</p><h3>Running your first code</h3><p>Finally, let’s write some code! We’ll do a kinda “Hello, World!” of data analytics: open a file, extract some data, print it, and plot a pretty picture. We’ll use the<a href="https://www.kaggle.com/datasets/rtatman/animal-bites"> Animal Bites</a> list from Kaggle.</p><p>Let’s load the data in. Add this code in the cell in your .ipynb file:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br>df = pd.read_csv(&quot;Health_AnimalBites.csv&quot;)</pre><p>Then press ‘Run’. Note that we’ve made sure our data is in the same directory as this notebook, so we’re using a root file path.</p><p>Womp womp. When I do this, I get an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fNBoFTs9UWO2ZWcaSzIqg.png" /></figure><p>Why? We haven’t installed pandas in this kernel yet. If we were using Anaconda that would be taken care of, but since we installed our notebook with pip, we need to do this manually here.</p><p>This is an important point to note about notebooks. They aren’t themselves all-in-one data analytics platforms. All a Jupyter notebook alone is doing is giving you an environment designed for better data analysis. It is just a better medium.</p><p>So, back in the terminal let’s pip install pandas matplotlib and then come back here and rerun this cell. To rerun something, click on the cell again, and click &#39;Run&#39;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsszqDke9SEPIpDG_FGucA.png" /></figure><p>Success! (if you count success as no errors, which every developer or analyst does.)</p><p>You should notice that the little In []: counter next to the cell has changed from 1 to 2. This tells you where this cell was run in comparison to other cells. For now, there is only this cell, but when you have dozens of cells you need to understand the order they were executed.</p><p>Now we start to come to the good part about notebooks. We don’t have any output from that code (it just reads data into memory), so the next obvious thing to do is something like df.head() to have a look at the structure of the data.</p><p>If we were doing this in a regular .py file that would be the next line. In a notebook, it is still the next line, but we can add it into the next cell, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I9eCwA0IEygKoCSa9QbEw.png" /></figure><p>Here’s something fun. If you were doing this in a script and trying to see that data in the terminal, you’d have to run print(df.head()). Instead, here the notebook already knows you want to see the data, so shows it to you. It even nicely formats it with a CSS table for better readability.</p><p>So we added that code to the next cell, selected only that cell, and then clicked ‘Run.’ This shows two important features of notebooks:</p><ol><li><strong>Variables are stored</strong>. We didn’t have to rerun that first cell to get df again, it was available to the second cell automatically.</li><li><strong>Cells can be run independently</strong>. If you think about how this might work in a .py file, you would always run the entire script each time. Not so with a notebook. You can run the analysis bit-by-bit, and even out of order, building up your exploration as you go.</li></ol><p>That second point brings up a quirk of notebooks. Cells are independent so you can run them in whatever order you want. What would happen if we ran the df.head() cell first, before the cell where that variable was initialized? We&#39;d get an error. For the most part, you aren&#39;t going to do this, but be wary of it as your notebooks expand-if you get an error message it might be because you&#39;re executing cells out of order.</p><p>Now that we have the dataframe already loaded in memory, we can write code in the cells below to perform any manipulation we want. For now, let’s just plot the species using pd.value_counts(df[&quot;SpeciesIDDesc&quot;]).plot(kind=&#39;barh&#39;):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OOn1jdVsAtKqaG6KKtQwA.png" /></figure><p>And there we have our plot, within our notebook. All the code, the data, and the outputs are all in one place, that we can then use to collaborate with others (by sharing the .ipynb file and underlying dataset) or to present the results.</p><p>As it stands, it might not look incredibly presentable. Good enough for a standup with the rest of the data team, but maybe not for sharing around the company, but in that screenshot above, there is a little easter egg. Just above pd.value_counts(df[&quot;SpeciesIDDesc&quot;]).plot(kind=&#39;barh&#39;) it says &#39;Now let&#39;s plot this data.&#39;</p><p>You see, cells aren’t only for code. They can also be for text. You can write any markdown you want in a cell, and have it appear within the notebook. Let’s do that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tb8kk33J3yhQYvJU95_8wg.png" /></figure><p>Now it’s looking a little better.</p><h3>Doing something useful with your notebook</h3><p>The example above is just to show you the concepts at work in a notebook. Now let’s build out a common workflow for an analyst. We’re going to recreate the report on ornithopter rental churn from the<a href="https://hex.tech/gallery/churn-monitor"> Hex gallery</a>. To do so, we’d want to:</p><ul><li>Import the data into our notebook</li><li>Interrogate the data to find some basic information about the dataset</li><li>Start exploring the data to learn more about each feature</li><li>Run some basic analysis to build a picture of the relative importance of each feature</li><li>Model out the features so we can use this dataset to predict future churn</li></ul><p>We’ll start again with importing the libraries we’re definitely going to use:</p><pre>import pandas as pd<br>import numpy as np</pre><p>Then we can import the data:</p><pre>churndata = pd.read_csv(&#39;churndata.csv&#39;)</pre><p>It is good practice to separate function calls to different cells. This way, you can see and debug the data from each function easily. Once we’ve got the data into a variable, we can start to look at it. Size, data types, and an actual look at some of the data is a good start:</p><pre>churndata.shape</pre><p>This gives the output:</p><pre>(2666, 22)</pre><p>So we have 2,666 rows and 22 columns.</p><p>Next, the data types of these columns:</p><pre>churndata.dtypes</pre><p>Output:</p><pre>Unnamed: 0                         int64<br>int64_field_0                      int64<br>division                          object<br>customer_length                  float64<br>interplanetary_plan                 bool<br>gold_support                        bool<br>number_support_reqs              float64<br>total_day_minutes                float64<br>total_day_sessions               float64<br>total_day_charge                 float64<br>total_eve_minutes                float64<br>total_eve_sessions               float64<br>total_eve_charge                 float64<br>total_night_minutes              float64<br>total_night_sessions             float64<br>total_night_charge               float64<br>total_interplanetary_minutes     float64<br>total_interplanetary_sessions    float64<br>total_interplanetary_charge      float64<br>repair_calls                     float64<br>churn                               bool<br>sector                            object<br>dtype: object</pre><p>Some ints, some bools, but mostly floats. So we know this is mostly a numeric dataset. Let’s have a look at it:</p><pre>churndata.head()</pre><p>We used pd.head() before as well-this method returns the first five rows of a dataset. It gives you an understanding of what the data looks like without having to print out all 2,666 rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mTIpygd_ZfvgvZJK72T7g.png" /></figure><p>Let’s start plotting some of this data to better understand it. First churn:</p><pre>pd.value_counts(churndata[&quot;churn&quot;]).plot(kind=&#39;barh&#39;)</pre><p>The output is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*7KjPvPFK1VDLD5c4F14d3Q.png" /></figure><p>pd.value_counts() is a helpful way to quickly a) get counts of categorical data within a dataset, and then combined with .plot(kind=&#39;barh&#39;), plotting that data.</p><p>As we have the churn numbers, we can also calculate the churn rate for the period:</p><pre>churn_rate = churn[1]/(churn[0]+churn[1])<br>print(churn_rate)</pre><p>Which gives an output of:</p><pre>0.145536384096024</pre><p>Let’s take a step back for a moment and talk about reporting. The graph above and the churn rate are exactly what you might want to include in a report. But in their present state, they aren’t particularly visually appealing.</p><p>This is how that data is presented in the Hex gallery version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*TOvRC9sFf-sOf9KpS9ii2Q.png" /></figure><p>Much nicer. Because of some limitations of Jupyter (for instance, no variables in markdown so no dynamic headers), we can’t make our output quite as nice, but we can make it clearer than it is.</p><p>First, let’s add the header. We can do that using a Markdown cell and a single # for an H1 header:</p><pre># Churn Monitor</pre><p>After that we can have another Markdown cell with the blurb:</p><pre>This made-up Dune ornithopter rental churn dashboard is an analog to the kind of dashboard you might make to model and track retention at a real company. Open the comments for explanations of cells. This is an example of a high complexity Hex app.</pre><p>Then we can start to include the data. For the churn rate, we’ll use an <a href="https://realpython.com/python-f-strings/">f-string</a> along with the data we’ve previously generated, along with working out the current quarter from today’s date:</p><pre>from datetime import date<br>quarter = f&quot;Q{pd.to_datetime(date.today()).quarter}&quot;<br>print(f&quot;{quarter} churn was {churn_rate*100:.2f}% with a total of {churn[1]} churned customers&quot;)</pre><p>Which will output:</p><pre>Q3 churn was 14.55% with a total of 388 churned customers</pre><p>Now we can spruce up our graph. You can plot data within a notebook using any viz library such as matplotlib or seaborn.</p><p>To create a similar chart with matplotlib we would first have to import matplotlib as we didn&#39;t do so at the top. That&#39;s OK, we can just do it now separately:</p><pre>import matplotlib.pyplot as plt</pre><p>(Just as with a regular file, <em>it is better</em> to put all your imports at the top, to help both you and anyone else using your notebook remember/understand the libraries you’ve used. Just remember to rerun that import cell before you try to use the library).</p><p>Then plot that data with a little styling:</p><pre>plt.style.use(&#39;ggplot&#39;)<br><br>x = [&#39;False&#39;, &#39;True&#39;]<br>count = [churn[0], churn[1]]<br><br>x_pos = [i for i, _ in enumerate(x)]<br><br>plt.bar(x_pos, count, color=[&#39;blue&#39;, &#39;orange&#39;])<br>plt.xlabel(&quot;Churned?&quot;)<br>plt.ylabel(&quot;Number of customers&quot;)<br>plt.title(&quot;Number of Customers by Churn Status&quot;)<br><br>plt.xticks(x_pos, x)<br><br>plt.show()</pre><p>Which outputs this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*YdQBpEZ8Fa2fAVmPuZLKHw.png" /></figure><p>Better than our attempt with just pandas. Now, if you tried to use all that you’ve coded so far in your notebook as a report, it still wouldn’t look that good. For one, it would be full of code. For some reporting, that is good-if you are talking to a data team, showing your working is important. But if you want a report on churn for the company to see, they don’t need to see how the sausage was made.</p><p>To build a report that looks like a report you need to convert your notebook to another format, such as html, and ask the preprocessor nicely to not include all the code. You do that will this command in the terminal:</p><pre>jupyter nbconvert --to html --no-input [notebook-name].ipynb</pre><p>This tells the converter (nbconvert) to output to html, but without all your input cells included. What this does is take this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*psR0kuKgDabsfkLbX12eBA.png" /></figure><p>And turn it into this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTHdxTCtNRNlVNV5eLaCkA.png" /></figure><p>Much better.</p><p>From here, the analytical world is your oyster. In the <a href="https://hex.tech/gallery/churn-monitor">Hex Gallery example</a>, we go on to perform some light machine learning to see what features predict churn. But you might want to explore each feature in more detail first, or build out interactive charts so your team can look at the data independently, or bring in other data to make this a more complete revenue metrics dashboard. With notebooks, you can do all of this, combining both the deep analysis and the metrics reporting in a single place.</p><h3>Going deeper on notebooks</h3><p>A few potential next steps:</p><h4>Connect to different data sources.</h4><p>Our example used a few local CSVs, but notebooks can connect to databases and data warehouses, cloud or otherwise. You could <a href="https://hex.tech/blog/connecting-snowflake-python/">connect to Snowflake </a>and then perform this exact same kind of analysis.</p><h4>Try extensions.</h4><p>Out-of-the-box, some aspects of Jupyter are limited (e.g. dynamic markdown). Extensions are add-ons that the community has built to improve utility. To install and use extensions run:</p><pre>pip install jupyter_contrib_nbextensions &amp;&amp; jupyter contrib nbextension install</pre><p>Then restart your notebook. You’ll have a new tab labeled nbextensions, where you can select different add-ons to improve your code or analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F50UrHl7SxI7KVaCJQr1Kw.png" /></figure><p>You can prettify your code or use Autopep8 to conform to guidelines. Or use the ‘hide input’ extension to perform the same function as the --no-input flag in nbconvert, but directly in your notebook.</p><h4>Build an entire report.</h4><p>This should be where you want to go next. Take the ideas and code here, use it on your data and build out two reports: the first for your data team where you show the full analysis, code-warts and all, and the second for wider distribution in your company where you use the ‘hide-input’ options and all the markdown cells to generate a report that showcases your work and data to the full.</p><p>Being able to perform your analysis line-by-line and step into the data at any point means that you can get a greater understanding of all your data. Being able to easily generate reports means that others will start to better understand your analysis as well.</p><p>Notebooks don’t replace good analysis. They just make it easier to “ <em>run code, explore data, present results</em>.”</p><p><em>Originally published at </em><a href="https://hex.tech/blog/beginners-guide-to-python-notebooks/"><em>https://hex.tech</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7f041b59b10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hex-blog/a-beginners-guide-to-python-notebooks-blog-hex-c7f041b59b10">A beginner’s guide to Python notebooks — Blog | Hex</a> was originally published in <a href="https://medium.com/hex-blog">The Hex Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>