<?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 Johannes Eckstein on Medium]]></title>
        <description><![CDATA[Stories by Johannes Eckstein on Medium]]></description>
        <link>https://medium.com/@digital.fireball?source=rss-533a27f9aa83------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lB--u3wWVHqpLTI3.jpg</url>
            <title>Stories by Johannes Eckstein on Medium</title>
            <link>https://medium.com/@digital.fireball?source=rss-533a27f9aa83------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:44:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@digital.fireball/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[Reactive event and Python backend driven Bokeh charts in Angular]]></title>
            <link>https://medium.com/data-science/reactive-event-and-python-backend-driven-bokeh-charts-in-angular-6fc23d608eeb?source=rss-533a27f9aa83------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fc23d608eeb</guid>
            <category><![CDATA[infographics]]></category>
            <category><![CDATA[bokeh]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[reactive]]></category>
            <dc:creator><![CDATA[Johannes Eckstein]]></dc:creator>
            <pubDate>Sat, 07 Mar 2020 15:39:06 GMT</pubDate>
            <atom:updated>2020-03-08T10:23:25.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVd1_CpblEctqghvI8lbZw.png" /><figcaption>cite.: taken from <a href="http://infographics.quantecdc.es:8080/dashboard">http://infographics.quantecdc.es:8080/dashboard</a></figcaption></figure><p>How you can overcome the drawbacks of ajax calls and make bokeh charts more reactive.</p><h3>Why data polling via Ajax Methods is a dead end</h3><p>Ajax calls from web-frontend side seem to be the quasi standard when it comes to regularly updated data views. But Ajax calls under the hood use the polling technique. This means the client asks every time-period on server side for new data via a http call which has several drawbacks:</p><ul><li>slows down the overall reactiveness of the view, especially when it comes to polling time below 50 ms.</li><li>the polling time is crucial when you have to decide before hand, which delay time you want to admit. If you want to have short time delay upon a data change event, polling is definitely not the best option.</li><li>even if data is not changing at all or stays inside non-critical bounds, the polling will go on forever, which is a extra load on the network and on the server especially when the data platform needs to scale up with the amount of data and view requests.</li></ul><p>These are also the reasons why an event-driven update technology will always outperform polling techniques. We will show you how this can be reached within an <a href="https://github.com/NuCOS/angular-bokeh">angular-bokeh</a> setup.</p><h3>Events in Angular</h3><p>Angular has implemented and is build upon an inherent event driven mechanism, that’s why it is evidently very attractive to combine Python’s async paradigm with Angular event detection.</p><p>On Python side the most mature web server which deals with async is aiohttp. It offers also a simple possibility to open up a websocket server onto which the Angular Client can connect to.</p><p>In our last article published on the combination of Angular with Bokeh charts, we sent the chart in json format via the websocket connection to angular. But had still relied on the ajax calls in order to update the charts since the BokehJS API offers mainly the black boxed embed method for embedding charts. After investigating the Bokeh-API a little bit deeper it seems very viable not to use the embed method but to go through the embedding step by step. Thus we have been able to extract the Bokeh Document object and from this object we got access to the data source.</p><p>Since there are very view examples available on the internet we decided to give a little bit of insight into what you can do with the source object and how you can use it to change the update paradigm to event driven.</p><h3>Source object update</h3><p>We are now focusing on the Angular side. After receiving the chart-item produced in Python in json format in item.doc we may produce a Bokeh document object with</p><pre>const doc = Bokeh.Document.from_json(item.doc);</pre><p>The source object can be extracted from the Document by the call</p><pre>const source = doc.get_model_by_name(&#39;my-tiles&#39;).data_source</pre><p>where it is important to use the same name ‘my-tiles’ also in the back-end for the data model. The embedding now works like</p><pre>const roots: Roots = {[item.root_id]: el}; Bokeh.embed.add_document_standalone(doc, el, roots, false);</pre><p>where the element is the Http-Element, which usually available by its id.</p><pre>const el = document.getElementById(id);</pre><p>The document in the line before has nothing to do with the Bokeh document, it’s just the global app document hook. Now that we have access to the source it is not so difficult to proceed with our usual event driven update.</p><pre>public getNumberChartData(source: any) { const callbackId = &#39;numberChartData&#39;; this.messageService.awaitMessage().pipe(filter(msg =&gt; msg.name === callbackId)) .subscribe( msg =&gt; { source.data.label[0] = msg.args.number; source.data.color = msg.args.color; source.change.emit(); }); }</pre><p>Whenever a relevant websocket message arrives in the MessageService, the source change event is called, which causes an inherent chart update. This subscription must be done only once for any new source and it should be made sure, that when the chart component is removed the subscription is unsubscribed.</p><h3>Python side: observer and observables</h3><p>When it comes to async programming, it seems that the best-practice examples must still be searched for. The async paradigm is confusing because it kind of breaks with simple futures and reduces the asynchronous programming effectively down to 3 things: async, await and somewhere the loop floating around. Since most examples tend to be singular and small it seems in the first place very difficult to setup a whole project to async especially if one tries to combine async and non-async functions. Sometimes it is even not possible to introduce async, e.g. for the often used <strong>init</strong> function. It simply does not accept an async in front.</p><p>Also it seems staggering, that the loop mainly serves as a long-lasting blocking call and everything what is inside the loop is to be concerned of and everything what is outside at that moment is out forever. Well that is not really true but according to our experience it is best practice if everything is inside the loop, when it comes to run_until_complete.</p><p>To switch to a fully event-driven paradigm, it will be much easier to setup if we introduce an observer-observable paradigm within the module nucosObs. Therefore we build a simple yet powerful observer mechanism, which allows to avoid distributing each method reference onto that place we want to call it. On the other hand we now have to distribute the observables which kind of carry the information for any observer that is listening on that observable. Also the way we react onto data inside the observables may be adjusted very easily afterwards and individually.</p><p>All observable are fed with data in so called interfaces.This can be for example a text input on the console or a websocket server. On the interface we may focus only how to get data from the source and feed it into the observable. This task then is totally separated from the task, what to do with data. In the legacy context usually a callback is connected to data, but even that is not necessary here.</p><p>The observers on the other hand are setup before starting the main loop call. But they include all kind of reactions inherently. They listen on the observable and parse that data for any purpose you want, even by calling subsequent methods. The parse function may be individualized very easily.</p><p>As a bonus the observers may be scheduled very easily for single or regular tasks.</p><p><em>Originally published at </em><a href="https://github.com/NuCOS/angular-bokeh/wiki/Reactive-event-driven-Bokeh-Charts"><em>https://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fc23d608eeb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reactive-event-and-python-backend-driven-bokeh-charts-in-angular-6fc23d608eeb">Reactive event and Python backend driven Bokeh charts in Angular</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Corona Virus Data Infographics]]></title>
            <link>https://medium.com/analytics-vidhya/corona-virus-data-infographics-8bf835641ced?source=rss-533a27f9aa83------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bf835641ced</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bokeh]]></category>
            <dc:creator><![CDATA[Johannes Eckstein]]></dc:creator>
            <pubDate>Tue, 03 Mar 2020 00:42:52 GMT</pubDate>
            <atom:updated>2020-03-06T08:17:34.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*N0tU-Rn2fDcQR68j.png" /></figure><p>as Dashboard:</p><p><a href="http://infographics.quantecdc.es:8080/dashboard">http://infographics.quantecdc.es:8080/dashboard</a></p><p>From January 2020 on the Corona virus started with some reported regional cases in China. Now at the end of February the disease is evidently revealed as being a worldwide phenomena, since it is spreading out easily in our interconnected world even with increasing speed recently.</p><p>The data source used for this infographics app is provided by the link <a href="https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset">https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset</a> with a permissive license CC0: Public Domain. The data was collected by Johns Hopkins University and from WHO, CDC, NHC and DXY in the first place. Thanks for the regular update.</p><h3>Presenting World Geographical Data</h3><p>To present the data e.g. the worldwide spread we make use of our recently proposed framework of Bokeh module in python together with the reactive Angular front-end. Both the back- and the front-end fit perfectly together. The data processing is done with high convenience in the python back-end, the charts could easily be created within the Bokeh module and then embedded in the front-end with even improved data control, since any event can now lead to a redraw of the presented data.</p><p>One interesting aspect of the Corona virus worldwide spread is the geographical location. Luckily the contours of all countries are available on github without any restrictive license ( <a href="https://github.com/johan/world.geo.json">https://github.com/johan/world.geo.json</a>). The contours may then be drawn as patches. In Bokeh this is done with some lines of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11cb817de575c93f32f3be9372ebf99f/href">https://medium.com/media/11cb817de575c93f32f3be9372ebf99f/href</a></iframe><p>The confirmed number of infections of the Corona virus we show by a half transparent circle in red color. The area should be mostly proportional to the counted number but since the outrages number of several ten-thousands of infections in China compared to numbers elsewhere of reported numbers less than 10 we have to make a compromise: the minimum radius is 1 and the maximum radius is 20 (in internal data-space units).</p><p>The position of the circles are connected to the country to which the number belongs. The coordinates of the countries we get from <em>Nominatim</em> which is provided in a python module named geopy.geocoders.</p><p>Since the data is inherently time dependent we made the date as a user selectable parameter. Thus the user may follow at least roughly the world wide spread by changing the date successively from the 22 of January when the data starts until today. As already said before: since the number of infections in China is overwhelming large the observation is a little bit biased. So let’s take a closer look on each country.</p><h3>Focus the Number of Confirmed Infections of each Country</h3><p>The time dependency may be better observed by extracting the data of each country individually. This is done in the bar chart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*NX31z73YqXPGMEa8.png" /></figure><p>Here we would like to present some techniques in pandas which may be helpful for working with this kind of data. Reading in <em>csv</em> data within pandas is as easy as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8cba6360eed021d05d3e45a05ff3305/href">https://medium.com/media/c8cba6360eed021d05d3e45a05ff3305/href</a></iframe><p>The second line changes the observation data column into a python <em>datetime</em> format which is in the end is a comparable object in contrast to a string date. Since we are not interested in the data of each city or province we accumulate the data with respect to the country column and the observation date column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b9c99bdb26bc50d1b38ac9ba113ffd/href">https://medium.com/media/65b9c99bdb26bc50d1b38ac9ba113ffd/href</a></iframe><p>To rearrange the index and create then again a separate country and date column we use the last three lines, which is also not so obvious with pandas. The user may now select one of the countries and receives the bar chart instantly.</p><h3>Events in Angular and Python</h3><p>Angular has implemented and is built upon an inherent event driven mechanism, that’s why it is evidently very attractive to combine Python’s <em>async</em> paradigm with Angular event detection.</p><p>On Python side the most mature web server which deals with <em>async</em> is <em>aiohttp</em>. It offers also a simple possibility to open up a <em>websocket</em> server onto which the Angular client can connect to.</p><p>Last time we have published the combination of Angular with Bokeh charts we sent the chart in json format via the <em>websocket</em> connection to angular. But we relied upon the <em>ajax</em> calls for update since the <em>BokehJS</em> API offers mainly the black boxed embed method for embedding charts. After investigating the API a little bit deeper it seems very viable not to use the embed method but to go through the embedding step by step. Thus we have been able to extract the bokeh Document object and from this object we got access to the data source.</p><p>Since there are very view examples available on the internet we decided to give a little bit of insight into what you can do with the source object and how we can in fact use it to change the update paradigm to event driven.</p><h3>Source Object Update</h3><p>We are now focusing on the Angular side. First of all we create a service in which we connect to the global Bokeh object</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f90859fb6f602cf53075022a6e0a744c/href">https://medium.com/media/f90859fb6f602cf53075022a6e0a744c/href</a></iframe><p>The Bokeh lib is inlcuded in the html file with the following two lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/482511b0a519720d382edc38e3fd5d9e/href">https://medium.com/media/482511b0a519720d382edc38e3fd5d9e/href</a></iframe><p>After receiving the chart-item produced in Python in <em>json</em> format as item we may produce a <em>bokeh</em> document object from which we can extract the most relevant document source</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c955fb903fe01f0fbc1d5e23cfcd790a/href">https://medium.com/media/c955fb903fe01f0fbc1d5e23cfcd790a/href</a></iframe><p>where it is important to use the same name ‘map-circles’ also in the backend for the data model. The actual embedding now works like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b0afa4730302f886991cc79bd2c56a5/href">https://medium.com/media/9b0afa4730302f886991cc79bd2c56a5/href</a></iframe><p>The third line is somehow mandatory for the hover tools to work properly. Now that we have access to the source it is not so difficult to proceed with our usual event driven update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4192d454b6cf411d4f3852f548272336/href">https://medium.com/media/4192d454b6cf411d4f3852f548272336/href</a></iframe><p>Whenever a relevant <em>websocket</em> message arrives in the <em>MessageService</em>, the source change event is emitted, which causes an inherent chart redraw event. This subscription must be done only once for any new source and it should be made sure, that when the chart component is removed the subscription is unsubscribed.</p><p>In our next article we will give more insight in the python back-end handling of the events. We will argue that from our point of view it has some advantages to use <em>websocket</em> connection since it gives also the possibility for displaying back-end events which would be impossible with a bare web api.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bf835641ced" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/corona-virus-data-infographics-8bf835641ced">Corona Virus Data Infographics</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building dynamic dashboards with Angular and Bokeh]]></title>
            <link>https://medium.com/data-science/building-dynamic-dashboards-with-angular-and-bokeh-51668a5367f1?source=rss-533a27f9aa83------2</link>
            <guid isPermaLink="false">https://medium.com/p/51668a5367f1</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[i40]]></category>
            <category><![CDATA[bokeh]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Johannes Eckstein]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 20:08:26 GMT</pubDate>
            <atom:updated>2020-01-15T20:08:26.824Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building dynamic dashboards in Python with Angular and Bokeh Charts</strong></h3><h4>A flexible and dynamic dashboard example using Bokeh Charts, Angular and Python as back-end.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*Uc5KW7hV3kPvueSuKKqVnA.png" /></figure><p>If we consider Industry 4.0 applications, in general, there are inevitable requirements for them.</p><p>They should be:</p><ul><li>modular,</li><li>extendable,</li><li>easy to integrate into existing networks and</li><li>interoperable - be easily connected to any other service.</li></ul><h3><strong>Dynamic chart example</strong></h3><p>One of the main objectives of such applications for example is the overview of data just in time, independent of the working platform. And the origin of the data should be of no technical relevance, may it come from other IoT devices like sensors or servers or other connected resources.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1pSXG8Q5g5Q%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1pSXG8Q5g5Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1pSXG8Q5g5Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd0fe07c2ac442436e8605eb89759d0b/href">https://medium.com/media/fd0fe07c2ac442436e8605eb89759d0b/href</a></iframe><p><strong>What we showed you already…</strong></p><p>Is that this can be achieved using <a href="https://towardsdatascience.com/angular-and-bokeh-e8acd86e7ab1">the web-app architecture</a> we presented previously on Medium.</p><h4><strong>Dynamic Dashboard Showcase</strong></h4><p>For that purpose we have built a dynamic dashboard with our recently proposed architecture. It consists of <a href="https://angular.io/">Angular</a> as a framework which has grown into a very mature front-end solution in the last few years. It offers nice standard components of web apps within <a href="https://material.angular.io/">Angular Material</a>, which can be extended easily to any more complex view or component.</p><p>For the back-end we stick, as always, to Python, because it offers all kinds of connectivity with very low development overhead and because it is simply a good language. Furthermore it offers a broad range of data processing tools like AI/Deep Learning Tools, Mathematical Tools and last but not least plotting tools like <a href="https://docs.bokeh.org/en/latest/">Bokeh</a>, which we are going to use in this presentation.</p><p>We are also very happy to extend our typically used web server technology with the asynchronous programming paradigm, that means we use <a href="https://aiohttp.readthedocs.io/en/stable/">aiohttp</a> as our standard python web server.</p><p>To connect both parts we decided to make extensive use of <a href="https://websockets.readthedocs.io/en/stable/">websockets</a>, which guarantees a responsive data stream in both directions via standard tcp/ip protocol.</p><p><strong>Problems to be solved</strong></p><p>Some typical problems which arise on the way are e.g.</p><ul><li>dynamic data provision within charts or number representation,</li><li>using independent Bokeh charts in the Angular app, each chart should be a component and the content of the chart is fully back-end driven,</li><li>flexibility - for example - to arrange charts on the board.</li></ul><h4><strong>Getting started with dynamic data provision</strong></h4><p>A dashboard must show data which can be updated at any time. In some situation we will need real-time data presentation or at least what is possible within the tcp/ip protocol processing time and the browser display time. We start with a slightly less strict requirement.</p><p>The easiest way to provide dynamic data for the chart is the use of ajax calls for Bokeh charts. Luckily this is already implemented as a standard way in Bokeh charts. Ajax data structures behave the same as usual data structures and may be used as a seamless way to update data in a regular interval.</p><p>Here we show how to update a number in a label. For that end we have to use <em>LabelSet</em> because that is the only dynamically updated data structure in combination with a text shown on the chart. We put the following code in a separate class <em>ChartProvider</em> in our Python back-end, which has then a function like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f54ef4c0d3fb50ab6ba1b48739fdb1fb/href">https://medium.com/media/f54ef4c0d3fb50ab6ba1b48739fdb1fb/href</a></iframe><p>This code snippet shows how the <em>source</em> may be updated every 300 ms and how the data is processed further within the <em>adapter</em> which is a small snippet of JavaScript Code. On Python side, the <em>AjaxDataSource</em> behaves mostly like every static data source which is of the format</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd2db17ae869d3692fed3fbaadc96c9b/href">https://medium.com/media/bd2db17ae869d3692fed3fbaadc96c9b/href</a></iframe><p>To provide continuous data the <em>ajax</em> way we must use an URL that is supported by our web server. As stated previously we use <em>aiohttp</em> and as such we may include this route as a POST route as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/809e27a9c442377666387b7becedd05d/href">https://medium.com/media/809e27a9c442377666387b7becedd05d/href</a></iframe><p>In the end, we can include the <em>chart_item</em> which comes out of a <em>ChartProvider</em> the same way we described in detail previously in our <a href="https://towardsdatascience.com/angular-and-bokeh-e8acd86e7ab1">article</a>. The chart_item is a <em>json</em> formatted chart which is self-contained. That means also that the chart has the data fetch mechanism <em>ajax</em> already included. In the following picture we see the chart figure included in a typical angular material card:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F49Wfhcje4DQ%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D49Wfhcje4DQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F49Wfhcje4DQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/093beebd051f8587200716b404fc56e1/href">https://medium.com/media/093beebd051f8587200716b404fc56e1/href</a></iframe><p>Bokeh provides an easy way of ajax updates. But sadly Bokeh has not yet a simple function, which only redraws the chart on <em>JavaScript</em> side. As a reminder, we use the call of the global included Bokeh module, which we import in our angular component via:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc608fccd877b64de05265c62fd6b122/href">https://medium.com/media/fc608fccd877b64de05265c62fd6b122/href</a></iframe><p>The main task on the angular side is to provide the data for the embed_item function call. Since we use a websocket connection, we send the chart_item from python to angular. It may also be provided by a REST-api. Our websocket connection, by the way, is more viable if we need data just in time from the server. The ajax call, on the other hand, is done by polling, which has several drawbacks. One of them is, the Webserver has worked every time the client asks for data even if the data has not changed.</p><p>So long story short. We can provide data like first chart data or other event-driven data via websocket but update data for the chart at the moment is limited to ajax calls. We would love to circumvent the ajax call in the future and switch to event-driven calls from back-end side. If you think about the solution, why not every time send the full chart via websocket and call the embed_item method, it is not a solution. The way Bokeh embeds the chart is very costly, thus we would never reach the update rate we would like to have.</p><h4><strong>Summary</strong></h4><p>We showed how to implement a periodically updated Bokeh chart within an Angular app, which is one part of our final goal that is to create a dynamic dashboard.</p><p>For the data update, we have used the ajax method because it is an already built-in method in Bokeh and we do not have to tweak our websocket connection.</p><p>On the python side the data provision is a more or less simple task but it is important that we make sure to use non blocking calls, that means a consistent use of asynchronous methods.</p><p>We will keep you updated soon on how to solve the other problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51668a5367f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-dynamic-dashboards-with-angular-and-bokeh-51668a5367f1">Building dynamic dashboards with Angular and Bokeh</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular and Bokeh]]></title>
            <link>https://medium.com/data-science/angular-and-bokeh-e8acd86e7ab1?source=rss-533a27f9aa83------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8acd86e7ab1</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[bokeh]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Johannes Eckstein]]></dc:creator>
            <pubDate>Sat, 09 Mar 2019 15:34:14 GMT</pubDate>
            <atom:updated>2021-01-22T10:49:01.314Z</atom:updated>
            <content:encoded><![CDATA[<p>We recently had the problem to display a chart figure of quality in an app or website. But additionally you want to be able to send update events from the python back-end and have all the nice interactions like button press- and text input- events coming with Angular, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*Uc5KW7hV3kPvueSuKKqVnA.png" /></figure><p>A Bokeh chart component might not always be the optimal solution, but even though - <a href="https://github.com/NuCOS/angular-bokeh">we would like to share with you</a> in this GitHub repository - what we think is a nice, minimal example and a demonstrator of how to integrate a python backend into an angular app.</p><h4>The starting point</h4><p>is the BokehJS lib which we integrate into an Angular project. The plotting data is provided by a websocket service, in our example we use aiohttp, but you may set up any other websocket connection. An angular component may be integrated anywhere in the html by its tag-name, the following snippet shows the Bokeh chart component</p><pre>&lt;bokeh-chart&gt;&lt;/bokeh-chart&gt;</pre><p>The bokeh-chart component is a regular angular component, with a html part</p><pre>&lt;div [id]=&quot;id&quot;&gt;&lt;/div&gt;</pre><p>and a typescript part. The chart component only needs to provide the id to its own html part. The data for the chart is provided by a service that is called right at the initialization of the component in <strong>ngOnInit</strong>. The relevant typescript part of the Bokeh chart component looks like</p><pre>...<br>export class BokehChartComponent implements OnInit {<br>  public id: string;<br><br>  constructor(<br>    private bokehService: BokehService) { }<br><br><br> ngOnInit() {<br>     this.id = &quot;chart&quot;;<br>     this.bokehService.getChart(this.id);<br> }<br>}</pre><p>Since the BokehJS lib has no types available, the integration in angular is not as straightforward as it should be. One has access to that lib only via the global exposed object of the lib, which in this case is also named <strong>Bokeh </strong>and which is the only hook which is necessary to embed a chart.</p><pre>// this is the global hook to the bokehjs lib (without types)<br>declare var Bokeh: any;</pre><p>This magic works only as expected if you plug in the usual java script into the topmost html file of the angular app <strong>index.html</strong></p><pre>&lt;head&gt;<br> ...<br>  &lt;link<br>    href=&quot;<a href="https://cdn.pydata.org/bokeh/release/bokeh-1.0.4.min.css">https://cdn.pydata.org/bokeh/release/bokeh-1.0.4.min.css</a>&quot;<br>    rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;<br>  &lt;script src=&quot;<a href="https://cdn.pydata.org/bokeh/release/bokeh-1.0.4.min.js">https://cdn.pydata.org/bokeh/release/bokeh-1.0.4.min.js</a>&quot;&gt;&lt;/script&gt;<br> &lt;/head&gt;</pre><h4>The BokehService</h4><p>provides the data for the chart via a <strong>MessageService</strong> which encapsulates the connection to the backend such that one only needs to send a proper formatted message by the exposed method sendMsg(msg).</p><pre>export class BokehService extends Connector {</pre><pre>constructor(private msgService: MessageService) {<br> super(‘BokehService’);<br> this.msgService.register(this);<br> }</pre><pre>…</pre><pre>public getChart(id: string) {<br> const msg = {<br> name: ‘addChart’,<br> args: [id],<br> action: ‘default’<br> };<br> this.msgService.sendMsg(msg);<br> }</pre><p>This service also exposes a method to the backend, that actually plots the chart into the native DOM-element, where we first have to delete the previous plots.</p><pre>public plot(msg: Message) {<br>      const id = msg.args.id;<br>      const el = document.getElementById(id);<br>      // first remove the previous charts as child<br>      // like this, bokeh does not let us update a chart<br>      while (el.hasChildNodes()) {<br>            el.removeChild(el.lastChild);<br>      }<br>      // be sure to include the correct dom-id as second argument<br>      Bokeh.embed.embed_item(msg.args.item, id);<br>    }</pre><h4>The back-end service</h4><p>in our example is written in python. We use aiohttp as an async solution for a web server. Right after starting the angular app in the browser, the angular WebsocketService connects immediately to the python backend on server side. Remember that in production you would implement more security on that point, like an authentication. The backend is ready to receive events from angular, like e.g. give me the data for the Bokeh chart.</p><p>The <strong>addChart</strong> which is called by the message from angular, sends the chartItem as a json item that connects to the websocket service</p><pre>    async def addChart(self, id_, user):<br>        &quot;&quot;&quot;<br>        Example for adding a bokeh chart from backend<br><br>        &quot;&quot;&quot;<br>        chartItem = self.chartProvider.chartExample()<br>        print(&quot;try to add chart for dom-id %s&quot; % id_)<br>        context = {&quot;name&quot;: &quot;BokehService&quot;,<br>                   &quot;args&quot;: {&quot;item&quot;: chartItem, &quot;id&quot;: id_},<br>                   &quot;action&quot;: &quot;plot&quot;}<br>        await self.send_event(json.dumps(context), user=user)</pre><p>The interesting part here is the send_event method which in fact is based on our implementation of the websocket server. As already mentioned, that part may differ in your individual implementation.</p><p>The minimal example for the chart, also written as a member function of <strong>ChartProvider</strong> class, looks very simple and just produces the data for a plain sin-plot in Bokeh</p><pre>import time<br>import numpy as np<br>from bokeh.plotting import figure<br>from bokeh.embed import json_item</pre><pre>class ChartProvider():</pre><pre>    def chartExample(self):<br>        t0 = time.time()<br>        # prepare some data<br>        self.phi += 0.02<br>        x = np.arange(0., 10., 0.1)<br>        y = np.sin(x + self.phi)<br>        # create a new plot<br>        p = figure()<br>        p.line(x, y, legend=&quot;SIN&quot;)<br>        chart_item = json_item(p)<br>        print(time.time()-t0)<br>        return chart_item</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8acd86e7ab1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/angular-and-bokeh-e8acd86e7ab1">Angular and Bokeh</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>