Bokeh – Developing with JavaScript ”; Previous Next The Bokeh Python library, and libraries for Other Languages such as R, Scala, and Julia, primarily interacts with BokehJS at a high level. A Python programmer does not have to worry about JavaScript or web development. However, one can use BokehJS API, to do pure JavaScript development using BokehJS directly. BokehJS objects such as glyphs and widgets are built more or less similarly as in Bokeh Python API. Typically, any Python ClassName is available as Bokeh.ClassName from JavaScript. For example, a Range1d object as obtained in Python. xrange = Range1d(start=-0.5, end=20.5) It is equivalently obtained with BokehJS as − var xrange = new Bokeh.Range1d({ start: -0.5, end: 20.5 }); Following JavaScript code when embedded in a HTML file renders a simple line plot in the browser. First include all BokehJS libraries in <head>..</head> secion of web page as below <head> <script type=”text/javascript” src=”https://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js”></script> <script type=”text/javascript” src=”https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js”></script> <script type=”text/javascript” src=”https://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js”></script> <script type=”text/javascript” src=”https://cdn.pydata.org/bokeh/release/bokeh-gl-1.3.4.min.js”></script> <script type=”text/javascript” src=”https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js”></script> <script type=”text/javascript” src=”https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js”></script> </head> In the body section following snippets of JavaScript construct various parts of a Bokeh Plot. <script> // create some data and a ColumnDataSource var x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10); var y = x.map(function (v) { return v * 0.5 + 3.0; }); var source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } }); // make the plot var plot = new Bokeh.Plot({ title: “BokehJS Plot”, plot_width: 400, plot_height: 400 }); // add axes to the plot var xaxis = new Bokeh.LinearAxis({ axis_line_color: null }); var yaxis = new Bokeh.LinearAxis({ axis_line_color: null }); plot.add_layout(xaxis, “below”); plot.add_layout(yaxis, “left”); // add a Line glyph var line = new Bokeh.Line({ x: { field: “x” }, y: { field: “y” }, line_color: “#666699″, line_width: 2 }); plot.add_glyph(line, source); Bokeh.Plotting.show(plot); </script> Save above code as a web page and open it in a browser of your choice. Print Page Previous Next Advertisements ”;
Category: bokeh
Bokeh – Discussion
Discuss Bokeh ”; Previous Next This tutorial will help you in understanding about Bokeh which is a data visualization library for Python. Here, you will learn about how to use Bokeh to create data applications, interactive plots and dashboards. Print Page Previous Next Advertisements ”;
Bokeh – Exporting Plots
Bokeh – Exporting Plots ”; Previous Next In addition to subcommands described above, Bokeh plots can be exported to PNG and SVG file format using export() function. For that purpose, local Python installation should have following dependency libraries. PhantomJS PhantomJS is a JavaScript API that enables automated navigation, screenshots, user behavior and assertions. It is used to run browser-based unit tests. PhantomJS is based on WebKit providing a similar browsing environment for different browsers and provides fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. In other words, PhantomJS is a web browser without a graphical user interface. Pillow Pillow, a Python Imaging Library (earlier known as PIL) is a free library for the Python programming language that provides support for opening, manipulating, and saving many different image file formats. (including PPM, PNG, JPEG, GIF, TIFF, and BMP.) Some of its features are per-pixel manipulations, masking and transparency handling, image filtering, image enhancing, etc. The export_png() function generates RGBA-format PNG image from layout. This function uses Webkit headless browser to render the layout in memory and then capture a screenshot. The generated image will be of the same dimensions as the source layout. Make sure that the Plot.background_fill_color and Plot.border_fill_color are properties to None. from bokeh.io import export_png export_png(plot, filename = “file.png”) It is possible that HTML5 Canvas plot output with a SVG element that can be edited using programs such as Adobe Illustrator. The SVG objects can also be converted to PDFs. Here, canvas2svg, a JavaScript library is used to mock the normal Canvas element and its methods with an SVG element. Like PNGs, in order to create a SVG with a transparent background,the Plot.background_fill_color and Plot.border_fill_color properties should be to None. The SVG backend is first activated by setting the Plot.output_backend attribute to “svg”. plot.output_backend = “svg” For headless export, Bokeh has a utility function, export_svgs(). This function will download all of SVG-enabled plots within a layout as distinct SVG files. from bokeh.io import export_svgs plot.output_backend = “svg” export_svgs(plot, filename = “plot.svg”) Print Page Previous Next Advertisements ”;
Bokeh – WebGL
Bokeh – WebGL ”; Previous Next When one has to use large datasets for creating visualizations with the help of Bokeh, the interaction can be very slow. For that purpose, one can enable Web Graphics Library (WebGL) support. WebGL is a JavaScript API that renders content in the browser using GPU (graphics processing unit). This standardized plugin is available in all modern browsers. To enable WebGL, all you have to do is set output_backend property of Bokeh Figure object to ‘webgl’. fig = figure(output_backend=”webgl”) In the following example, we plot a scatter glyph consisting of 10,000 points with the help of WebGL support. import numpy as np from bokeh.plotting import figure, show, output_file N = 10000 x = np.random.normal(0, np.pi, N) y = np.sin(x) + np.random.normal(0, 0.2, N) output_file(“scatterWebGL.html”) p = figure(output_backend=”webgl”) p.scatter(x, y, alpha=0.1) show(p) Output Print Page Previous Next Advertisements ”;
Bokeh – Plot Tools
Bokeh – Plot Tools ”; Previous Next When a Bokeh plot is rendered, normally a tool bar appears on the right side of the figure. It contains a default set of tools. First of all, the position of toolbar can be configured by toolbar_location property in figure() function. This property can take one of the following values − “above” “below” “left” “right” “None” For example, following statement will cause toolbar to be displayed below the plot − Fig = figure(toolbar_location = “below”) This toolbar can be configured according to the requirement by adding required from various tools defined in bokeh.models module. For example − Fig.add_tools(WheelZoomTool()) The tools can be classified under following categories − Pan/Drag Tools Click/Tap Tools Scroll/Pinch Tools Tool Description Icon BoxSelectTool Name : ”box_select” allows the user to define a rectangular selection region by left-dragging a mouse LassoSelectTool name: ”lasso_select allows the user to define an arbitrary region for selection by left-dragging a mouse PanTool name: ”pan”, ”xpan”, ”ypan”, allows the user to pan the plot by left-dragging a mouse TapTool name: ”tap allows the user to select at single points by clicking a left mouse button WheelZoomTool name: ”wheel_zoom”, ”xwheel_zoom”, ”ywheel_zoom” zoom the plot in and out, centered on the current mouse location. WheelPanTool name: ”xwheel_pan”, ”ywheel_pan” translate the plot window along the specified dimension without changing the window’s aspect ratio. ResetTool name: ”reset” restores the plot ranges to their original values. SaveTool name: ”save” allows the user to save a PNG image of the plot. ZoomInTool name: ”zoom_in”, ”xzoom_in”, ”yzoom_in” The zoom-in tool will increase the zoom of the plot in x, y or both coordinates ZoomOutTool name: ”zoom_out”, ”xzoom_out”, ”yzoom_out” The zoom-out tool will decrease the zoom of the plot in x, y or both coordinates CrosshairTool name: ”crosshair” draws a crosshair annotation over the plot, centered on the current mouse position. Print Page Previous Next Advertisements ”;
Bokeh – Embedding Plots and Apps ”; Previous Next Plots and data in the form of standalone documents as well as Bokeh applications can be embedded in HTML documents. Standalone document is a Bokeh plot or document not backed by Bokeh server. The interactions in such a plot is purely in the form of custom JS and not Pure Python callbacks. Bokeh plots and documents backed by Bokeh server can also be embedded. Such documents contain Python callbacks that run on the server. In case of standalone documents, a raw HTML code representing a Bokeh plot is obtained by file_html() function. from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.embed import file_html fig = figure() fig.line([1,2,3,4,5], [3,4,5,2,3]) string = file_html(plot, CDN, “my plot”) Return value of file_html() function may be saved as HTML file or may be used to render through URL routes in Flask app. In case of standalone document, its JSON representation can be obtained by json_item() function. from bokeh.plotting import figure from bokeh.embed import file_html import json fig = figure() fig.line([1,2,3,4,5], [3,4,5,2,3]) item_text = json.dumps(json_item(fig, “myplot”)) This output can be used by the Bokeh.embed.embed_item function on a webpage − item = JSON.parse(item_text); Bokeh.embed.embed_item(item); Bokeh applications on Bokeh Server may also be embedded so that a new session and Document is created on every page load so that a specific, existing session is loaded. This can be accomplished with the server_document() function. It accepts the URL to a Bokeh server application, and returns a script that will embed new sessions from that server any time the script is executed. The server_document() function accepts URL parameter. If it is set to ‘default’, the default URL http://localhost:5006/ will be used. from bokeh.embed import server_document script = server_document(“http://localhost:5006/sliders”) The server_document() function returns a script tag as follows − <script src=”http://localhost:5006/sliders/autoload.js?bokeh-autoload-element=1000&bokeh-app-path=/sliders&bokeh-absolute-url=https://localhost:5006/sliders” id=”1000″> </script> Print Page Previous Next Advertisements ”;
Bokeh – Extending Bokeh
Bokeh – Extending Bokeh ”; Previous Next Bokeh integrates well with a wide variety of other libraries, allowing you to use the most appropriate tool for each task. The fact that Bokeh generates JavaScript, makes it possible to combine Bokeh output with a wide variety of JavaScript libraries, such as PhosphorJS. Datashader (https://github.com/bokeh/datashader) is another library with which Bokeh output can be extended. It is a Python library that pre-renders large datasets as a large-sized raster image. This ability overcomes limitation of browser when it comes to very large data. Datashader includes tools to build interactive Bokeh plots that dynamically re-render these images when zooming and panning in Bokeh, making it practical to work with arbitrarily large datasets in a web browser. Another library is Holoviews ((http://holoviews.org/) that provides a concise declarative interface for building Bokeh plots, especially in Jupyter notebook. It facilitates quick prototyping of figures for data analysis. Print Page Previous Next Advertisements ”;
Bokeh – Server
Bokeh – Server ”; Previous Next Bokeh architecture has a decouple design in which objects such as plots and glyphs are created using Python and converted in JSON to be consumed by BokehJS client library. However, it is possible to keep the objects in python and in the browser in sync with one another with the help of Bokeh Server. It enables response to User Interface (UI) events generated in a browser with the full power of python. It also helps automatically push server-side updates to the widgets or plots in a browser. A Bokeh server uses Application code written in Python to create Bokeh Documents. Every new connection from a client browser results in the Bokeh server creating a new document, just for that session. First, we have to develop an application code to be served to client browser. Following code renders a sine wave line glyph. Along with the plot, a slider control is also rendered to control the frequency of sine wave. The callback function update_data() updates ColumnDataSource data taking the instantaneous value of slider as current frequency. import numpy as np from bokeh.io import curdoc from bokeh.layouts import row, column from bokeh.models import ColumnDataSource from bokeh.models.widgets import Slider, TextInput from bokeh.plotting import figure N = 200 x = np.linspace(0, 4*np.pi, N) y = np.sin(x) source = ColumnDataSource(data = dict(x = x, y = y)) plot = figure(plot_height = 400, plot_width = 400, title = “sine wave”) plot.line(”x”, ”y”, source = source, line_width = 3, line_alpha = 0.6) freq = Slider(title = “frequency”, value = 1.0, start = 0.1, end = 5.1, step = 0.1) def update_data(attrname, old, new): a = 1 b = 0 w = 0 k = freq.value x = np.linspace(0, 4*np.pi, N) y = a*np.sin(k*x + w) + b source.data = dict(x = x, y = y) freq.on_change(”value”, update_data) curdoc().add_root(row(freq, plot, width = 500)) curdoc().title = “Sliders” Next, start Bokeh server by following command line − Bokeh serve –show sliders.py Bokeh server starts running and serving the application at localhost:5006/sliders. The console log shows the following display − C:UsersUser>bokeh serve –show scriptssliders.py 2019-09-29 00:21:35,855 Starting Bokeh server version 1.3.4 (running on Tornado 6.0.3) 2019-09-29 00:21:35,875 Bokeh app running at: http://localhost:5006/sliders 2019-09-29 00:21:35,875 Starting Bokeh server with process id: 3776 2019-09-29 00:21:37,330 200 GET /sliders (::1) 699.99ms 2019-09-29 00:21:38,033 101 GET /sliders/ws?bokeh-protocol-version=1.0&bokeh-session-id=VDxLKOzI5Ppl9kDvEMRzZgDVyqnXzvDWsAO21bRCKRZZ (::1) 4.00ms 2019-09-29 00:21:38,045 WebSocket connection opened 2019-09-29 00:21:38,049 ServerConnection created Open your favourite browser and enter above address. The Sine wave plot is displayed as follows − You can try and change the frequency to 2 by rolling the slider. Print Page Previous Next Advertisements ”;
Bokeh – Quick Guide
Bokeh – Quick Guide ”; Previous Next Bokeh – Introduction Bokeh is a data visualization library for Python. Unlike Matplotlib and Seaborn, they are also Python packages for data visualization, Bokeh renders its plots using HTML and JavaScript. Hence, it proves to be extremely useful for developing web based dashboards. The Bokeh project is sponsored by NumFocus https://numfocus.org/. NumFocus also supports PyData, an educational program, involved in development of other important tools such as NumPy, Pandas and more. Bokeh can easily connect with these tools and produce interactive plots, dashboards and data applications. Features Bokeh primarily converts the data source into a JSON file which is used as input for BokehJS, a JavaScript library, which in turn is written in TypeScript and renders the visualizations in modern browsers. Some of the important features of Bokeh are as follows − Flexibility Bokeh is useful for common plotting requirements as well as custom and complex use-cases. Productivity Bokeh can easily interact with other popular Pydata tools such as Pandas and Jupyter notebook. Interactivity This is an important advantage of Bokeh over Matplotlib and Seaborn, both produce static plots. Bokeh creates interactive plots that change when the user interacts with them. You can give your audience a wide range of options and tools for inferring and looking at data from various angles so that user can perform “what if” analysis. Powerful By adding custom JavaScript, it is possible to generate visualizations for specialised use-cases. Sharable Plots can be embedded in output of Flask or Django enabled web applications. They can also be rendered in Jupyter notebooks. Open source Bokeh is an open source project. It is distributed under Berkeley Source Distribution (BSD) license. Its source code is available on https://github.com/bokeh/bokeh. Bokeh – Environment Setup Bokeh can be installed on CPython versions 2.7 and 3.5+ only both with Standard distribution and Anaconda distribution. Current version of Bokeh at the time of writing this tutorial is ver. 1.3.4. Bokeh package has the following dependencies − jinja2 >= 2.7 numpy >= 1.7.1 packaging >= 16.8 pillow >= 4.0 python-dateutil >= 2.1 pyyaml >= 3.10 six >= 1.5.2 tornado >= 4.3 Generally, above packages are installed automatically when Bokeh is installed using Python’s built-in Package manager PIP as shown below − pip3 install bokeh If you are using Anaconda distribution, use conda package manager as follows − conda install bokeh In addition to the above dependencies, you may require additional packages such as pandas, psutil, etc., for specific purposes. To verify if Bokeh has been successfully installed, import bokeh package in Python terminal and check its version − >>> import bokeh >>> bokeh.__version__ ”1.3.4” Bokeh – Getting Started Creating a simple line plot between two numpy arrays is very simple. To begin with, import following functions from bokeh.plotting modules − from bokeh.plotting import figure, output_file, show The figure() function creates a new figure for plotting. The output_file() function is used to specify a HTML file to store output. The show() function displays the Bokeh figure in browser on in notebook. Next, set up two numpy arrays where second array is sine value of first. import numpy as np import math x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) To obtain a Bokeh Figure object, specify the title and x and y axis labels as below − p = figure(title = “sine wave example”, x_axis_label = ”x”, y_axis_label = ”y”) The Figure object contains a line() method that adds a line glyph to the figure. It needs data series for x and y axes. p.line(x, y, legend = “sine”, line_width = 2) Finally, set the output file and call show() function. output_file(“sine.html”) show(p) This will render the line plot in ‘sine.html’ and will be displayed in browser. Complete code and its output is as follows from bokeh.plotting import figure, output_file, show import numpy as np import math x = np.arange(0, math.pi*2, 0.05) y = np.sin(x) output_file(“sine.html”) p = figure(title = “sine wave example”, x_axis_label = ”x”, y_axis_label = ”y”) p.line(x, y, legend = “sine”, line_width = 2) show(p) Output on browser Bokeh – Jupyter Notebook Displaying Bokeh figure in Jupyter notebook is very similar to the above. The only change you need to make is to import output_notebook instead of output_file from bokeh.plotting module. from bokeh.plotting import figure, output_notebook, show Call to output_notebook() function sets Jupyter notebook’s output cell as the destination for show() function as shown below − output_notebook() show(p) Enter the code in a notebook cell and run it. The sine wave will be displayed inside the notebook. Bokeh – Basic Concepts Bokeh package offers two interfaces using which various plotting operations can be performed. bokeh.models This module is a low level interface. It provides great deal of flexibility to the application developer in developing visualizations. A Bokeh plot results in an object containing visual and data aspects of a scene which is used by BokehJS library. The low-level objects that comprise a Bokeh scene graph are called Models. bokeh.plotting This is a higher level interface that has functionality for composing visual glyphs. This module contains definition of Figure class. It actually is a subclass of plot class defined in bokeh.models module. Figure class simplifies plot creation. It contains various methods to draw different vectorized graphical glyphs. Glyphs are the building blocks of Bokeh plot such as lines, circles, rectangles, and other shapes. bokeh.application Bokeh package Application class which is a lightweight factory for creating Bokeh Documents. A Document is a container for Bokeh Models to be reflected to the client side BokehJS library. bokeh.server It provides customizable Bokeh Server Tornadocore application. Server is used to share and publish interactive plots and apps to an audience of your choice. Bokeh – Plots with Glyphs Any plot is usually made up of one or many geometrical shapes such as line, circle, rectangle, etc. These shapes have visual information about the corresponding set of data. In Bokeh terminology, these geometrical shapes are called gylphs. Bokeh plots constructed using bokeh.plotting interface use a default set
Bokeh – Useful Resources
Bokeh – Useful Resources ”; Previous Next The following resources contain additional information on Bokeh. Please use them to get more in-depth knowledge on this. Useful Video Courses Data Analytics: Python Visualizations Featured 43 Lectures 6.5 hours MANAS DASGUPTA More Detail Develop and Deploy Data Science Web Apps with Streamlit 60 Lectures 4.5 hours Srikanth Guskra More Detail Create A Sci-Fi Android On Fire In Photoshop 16 Lectures 2 hours Adrian Scheff More Detail Create A Devil On Fire Composition In Affinity Photo 38 Lectures 5 hours Adrian Scheff More Detail PyScript – Learn to Run Python in your Browser”s HTML Most Popular 31 Lectures 1 hours Prince Patni More Detail Spatial Data Visualization and Machine Learning in Python Best Seller 21 Lectures 4.5 hours Edwin Bomela More Detail Print Page Previous Next Advertisements ”;