Bokeh – Using Bokeh Subcommands ”; Previous Next The Bokeh application provides a number of subcommands to be executed from command line. Following table shows the subcommands − 1 Html Create HTML files for one or more applications 2 info print information of Bokeh server configuration 3 json Create JSON files for one or more applications 4 png Create PNG files for one or more applications 5 sampledata Download the bokeh sample data sets 6 secret Create a Bokeh secret key for use with Bokeh server 7 serve Run a Bokeh server hosting one or more applications 8 static Serve static assets (JavaScript, CSS, images, fonts, etc.) used by BokeJS library 9 svg Create SVG files for one or more applications Following command generates a HTML file for Python script having a Bokeh figure. C:python37>bokeh html -o app.html app.py Adding show option automatically opens the HTML file in browser. Likewise, Python script is converted to PNG, SVG, JSON files with corresponding subcommand. To display information of Bokeh server, use info subcommand as follows − C:python37>bokeh info Python version : 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] IPython version : (not installed) Tornado version : 6.0.3 Bokeh version : 1.3.4 BokehJS static path : c:python37libsite-packagesbokehserverstatic node.js version : (not installed) npm version : (not installed) In order to experiment with various types of plots, Bokeh website https://bokeh.pydata.org makes available sample datasets. They can be downloaded to local machine by sampledata subcommand. C:python37>bokeh info Following datasets are downloaded in C:UsersUser.bokehdata folder − AAPL.csv airports.csv airports.json CGM.csv FB.csv gapminder_fertility.csv gapminder_life_expectancy.csv gapminder_population.csv gapminder_regions.csv GOOG.csv haarcascade_frontalface_default.xml IBM.csv movies.db MSFT.csv routes.csv unemployment09.csv us_cities.json US_Counties.csv world_cities.csv WPP2012_SA_DB03_POPULATION_QUINQUENNIAL.csv The secret subcommand generates a secret key to be used along with serve subcommand with SECRET_KEY environment variable. Print Page Previous Next Advertisements ”;
Category: bokeh
Bokeh – Pandas
Bokeh – Pandas ”; Previous Next In all the examples above, the data to be plotted has been provided in the form of Python lists or numpy arrays. It is also possible to provide the data source in the form of pandas DataFrame object. DataFrame is a two-dimensional data structure. Columns in the dataframe can be of different data types. The Pandas library has functions to create dataframe from various sources such as CSV file, Excel worksheet, SQL table, etc. For the purpose of following example, we are using a CSV file consisting of two columns representing a number x and 10x. The test.csv file is as below − x,pow 0.0,1.0 0.5263157894736842,3.3598182862837818 1.0526315789473684,11.28837891684689 1.5789473684210527,37.926901907322495 2.1052631578947367,127.42749857031335 2.631578947368421,428.1332398719391 3.1578947368421053,1438.449888287663 3.6842105263157894,4832.930238571752 4.2105263157894735,16237.76739188721 4.7368421052631575,54555.947811685146 We shall read this file in a dataframe object using read_csv() function in pandas. import pandas as pd df = pd.read_csv(”test.csv”) print (df) The dataframe appears as below − x pow 0 0.000000 1.000000 1 0.526316 3.359818 2 1.052632 11.288379 3 1.578947 37.926902 4 2.105263 127.427499 5 2.631579 428.133240 6 3.157895 1438.449888 7 3.684211 4832.930239 8 4.210526 16237.767392 9 4.736842 54555.947812 The ‘x’ and ‘pow’ columns are used as data series for line glyph in bokeh plot figure. from bokeh.plotting import figure, output_file, show p = figure() x = df[”x”] y = df[”pow”] p.line(x,y,line_width = 2) p.circle(x, y,size = 20) show(p) Output Print Page Previous Next Advertisements ”;
Bokeh – Layouts
Bokeh – Layouts ”; Previous Next Bokeh visualizations can be suitably arranged in different layout options. These layouts as well as sizing modes result in plots and widgets resizing automatically as per the size of browser window. For consistent appearance, all items in a layout must have same sizing mode. The widgets (buttons, menus, etc.) are kept in a separate widget box and not in plot figure. First type of layout is Column layout which displays plot figures vertically. The column() function is defined in bokeh.layouts module and takes following signature − from bokeh.layouts import column col = column(children, sizing_mode) children − List of plots and/or widgets. sizing_mode − determines how items in the layout resize. Possible values are “fixed”, “stretch_both”, “scale_width”, “scale_height”, “scale_both”. Default is “fixed”. Following code produces two Bokeh figures and places them in a column layout so that they are displayed vertically. Line glyphs representing sine and cos relationship between x and y data series is displayed in Each figure. from bokeh.plotting import figure, output_file, show from bokeh.layouts import column import numpy as np import math x = np.arange(0, math.pi*2, 0.05) y1 = np.sin(x) y2 = np.cos(x) fig1 = figure(plot_width = 200, plot_height = 200) fig1.line(x, y1,line_width = 2, line_color = ”blue”) fig2 = figure(plot_width = 200, plot_height = 200) fig2.line(x, y2,line_width = 2, line_color = ”red”) c = column(children = [fig1, fig2], sizing_mode = ”stretch_both”) show(c) Output Similarly, Row layout arranges plots horizontally, for which row() function as defined in bokeh.layouts module is used. As you would think, it also takes two arguments (similar to column() function) – children and sizing_mode. The sine and cos curves as shown vertically in above diagram are now displayed horizontally in row layout with following code from bokeh.plotting import figure, output_file, show from bokeh.layouts import row import numpy as np import math x = np.arange(0, math.pi*2, 0.05) y1 = np.sin(x) y2 = np.cos(x) fig1 = figure(plot_width = 200, plot_height = 200) fig1.line(x, y1,line_width = 2, line_color = ”blue”) fig2 = figure(plot_width = 200, plot_height = 200) fig2.line(x, y2,line_width = 2, line_color = ”red”) r = row(children = [fig1, fig2], sizing_mode = ”stretch_both”) show(r) Output The Bokeh package also has grid layout. It holds multiple plot figures (as well as widgets) in a two dimensional grid of rows and columns. The gridplot() function in bokeh.layouts module returns a grid and a single unified toolbar which may be positioned with the help of toolbar_location property. This is unlike row or column layout where each plot shows its own toolbar. The grid() function too uses children and sizing_mode parameters where children is a list of lists. Ensure that each sublist is of same dimensions. In the following code, four different relationships between x and y data series are plotted in a grid of two rows and two columns. from bokeh.plotting import figure, output_file, show from bokeh.layouts import gridplot import math x = list(range(1,11)) y1 = x y2 =[11-i for i in x] y3 = [i*i for i in x] y4 = [math.log10(i) for i in x] fig1 = figure(plot_width = 200, plot_height = 200) fig1.line(x, y1,line_width = 2, line_color = ”blue”) fig2 = figure(plot_width = 200, plot_height = 200) fig2.circle(x, y2,size = 10, color = ”green”) fig3 = figure(plot_width = 200, plot_height = 200) fig3.circle(x,y3, size = 10, color = ”grey”) fig4 = figure(plot_width = 200, plot_height = 200, y_axis_type = ”log”) fig4.line(x,y4, line_width = 2, line_color = ”red”) grid = gridplot(children = [[fig1, fig2], [fig3,fig4]], sizing_mode = ”stretch_both”) show(grid) Output Print Page Previous Next Advertisements ”;
Bokeh – Customising legends
Bokeh – Customising legends ”; Previous Next Various glyphs in a plot can be identified by legend property appear as a label by default at top-right position of the plot area. This legend can be customised by following attributes − 1 legend.label_text_font change default label font to specified font name 2 legend.label_text_font_size font size in points 3 legend.location set the label at specified location. 4 legend.title set title for legend label 5 legend.orientation set to horizontal (default) or vertical 6 legend.clicking_policy specify what should happen when legend is clicked hide: hides the glyph corresponding to legend mute: mutes the glyph corresponding to legendtd> Example Example code for legend customisation is as follows − from bokeh.plotting import figure, output_file, show import math x2 = list(range(1,11)) y4 = [math.pow(i,2) for i in x2] y2 = [math.log10(pow(10,i)) for i in x2] fig = figure(y_axis_type = ”log”) fig.circle(x2, y2,size = 5, color = ”blue”, legend = ”blue circle”) fig.line(x2,y4, line_width = 2, line_color = ”red”, legend = ”red line”) fig.legend.location = ”top_left” fig.legend.title = ”Legend Title” fig.legend.title_text_font = ”Arial” fig.legend.title_text_font_size = ”20pt” show(fig) Output Print Page Previous Next Advertisements ”;
Bokeh – Filtering Data
Bokeh – Filtering Data ”; Previous Next Often, you may want to obtain a plot pertaining to a part of data that satisfies certain conditions instead of the entire dataset. Object of the CDSView class defined in bokeh.models module returns a subset of ColumnDatasource under consideration by applying one or more filters over it. IndexFilter is the simplest type of filter. You have to specify indices of only those rows from the dataset that you want to use while plotting the figure. Following example demonstrates use of IndexFilter to set up a CDSView. The resultant figure shows a line glyph between x and y data series of the ColumnDataSource. A view object is obtained by applying index filter over it. The view is used to plot circle glyph as a result of IndexFilter. Example from bokeh.models import ColumnDataSource, CDSView, IndexFilter from bokeh.plotting import figure, output_file, show source = ColumnDataSource(data = dict(x = list(range(1,11)), y = list(range(2,22,2)))) view = CDSView(source=source, filters = [IndexFilter([0, 2, 4,6])]) fig = figure(title = ”Line Plot example”, x_axis_label = ”x”, y_axis_label = ”y”) fig.circle(x = “x”, y = “y”, size = 10, source = source, view = view, legend = ”filtered”) fig.line(source.data[”x”],source.data[”y”], legend = ”unfiltered”) show(fig) Output To choose only those rows from the data source, that satisfy a certain Boolean condition, apply a BooleanFilter. A typical Bokeh installation consists of a number of sample data sets in sampledata directory. For following example, we use unemployment1948 dataset provided in the form of unemployment1948.csv. It stores year wise percentage of unemployment in USA since 1948. We want to generate a plot only for year 1980 onwards. For that purpose, a CDSView object is obtained by applying BooleanFilter over the given data source. from bokeh.models import ColumnDataSource, CDSView, BooleanFilter from bokeh.plotting import figure, show from bokeh.sampledata.unemployment1948 import data source = ColumnDataSource(data) booleans = [True if int(year) >= 1980 else False for year in source.data[”Year”]] print (booleans) view1 = CDSView(source = source, filters=[BooleanFilter(booleans)]) p = figure(title = “Unemployment data”, x_range = (1980,2020), x_axis_label = ”Year”, y_axis_label=”Percentage”) p.line(x = ”Year”, y = ”Annual”, source = source, view = view1, color = ”red”, line_width = 2) show(p) Output To add more flexibility in applying filter, Bokeh provides a CustomJSFilter class with the help of which the data source can be filtered with a user defined JavaScript function. The example given below uses the same USA unemployment data. Defining a CustomJSFilter to plot unemployment figures of year 1980 and after. from bokeh.models import ColumnDataSource, CDSView, CustomJSFilter from bokeh.plotting import figure, show from bokeh.sampledata.unemployment1948 import data source = ColumnDataSource(data) custom_filter = CustomJSFilter(code = ””” var indices = []; for (var i = 0; i < source.get_length(); i++){ if (parseInt(source.data[”Year”][i]) > = 1980){ indices.push(true); } else { indices.push(false); } } return indices; ”””) view1 = CDSView(source = source, filters = [custom_filter]) p = figure(title = “Unemployment data”, x_range = (1980,2020), x_axis_label = ”Year”, y_axis_label = ”Percentage”) p.line(x = ”Year”, y = ”Annual”, source = source, view = view1, color = ”red”, line_width = 2) show(p) Print Page Previous Next Advertisements ”;
Bokeh – Rectangle, Oval and Polygon ”; Previous Next It is possible to render rectangle, ellipse and polygons in a Bokeh figure. The rect() method of Figure class adds a rectangle glyph based on x and y coordinates of center, width and height. The square() method on the other hand has size parameter to decide dimensions. The ellipse() and oval() methods adds an ellipse and oval glyph. They use similar signature to that of rect() having x, y,w and h parameters. Additionally, angle parameter determines rotation from horizontal. Example Following code shows use of different shape glyph methods − from bokeh.plotting import figure, output_file, show fig = figure(plot_width = 300, plot_height = 300) fig.rect(x = 10,y = 10,width = 100, height = 50, width_units = ”screen”, height_units = ”screen”) fig.square(x = 2,y = 3,size = 80, color = ”red”) fig.ellipse(x = 7,y = 6, width = 30, height = 10, fill_color = None, line_width = 2) fig.oval(x = 6,y = 6,width = 2, height = 1, angle = -0.4) show(fig) Output Print Page Previous Next Advertisements ”;
Bokeh – Jupyter Notebook
Bokeh – Jupyter Notebook ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Bokeh – Specialized Curves
Bokeh – Specialized Curves ”; Previous Next The bokeh.plotting API supports methods for rendering following specialised curves − beizer() This method adds a Bézier curve to the figure object. A Bézier curve is a parametric curve used in computer graphics. Other uses include the design of computer fonts and animation, user interface design and for smoothing cursor trajectory. In vector graphics, Bézier curves are used to model smooth curves that can be scaled indefinitely. A “Path” is combination of linked Bézier curves. The beizer() method has following parameters which are defined − 1 x0 The x-coordinates of the starting points. 2 y0 The y-coordinates of the starting points.. 3 x1 The x-coordinates of the ending points. 4 y1 The y-coordinates of the ending points. 5 cx0 The x-coordinates of first control points. 6 cy0 The y-coordinates of first control points. 7 cx1 The x-coordinates of second control points. 8 cy1 The y-coordinates of second control points. Default value for all parameters is None. Example Following code generates a HTML page showing a Bézier curve and parabola in Bokeh plot − x = 2 y = 4 xp02 = x+0.4 xp01 = x+0.1 xm01 = x-0.1 yp01 = y+0.2 ym01 = y-0.2 fig = figure(plot_width = 300, plot_height = 300) fig.bezier(x0 = x, y0 = y, x1 = xp02, y1 = y, cx0 = xp01, cy0 = yp01, cx1 = xm01, cy1 = ym01, line_color = “red”, line_width = 2) Output quadratic() This method adds a parabola glyph to bokeh figure. The function has same parameters as beizer(), except cx0 and cx1. Example The code given below generates a quadratic curve. x = 2 y = 4 xp02 = x + 0.3 xp01 = x + 0.2 xm01 = x – 0.4 yp01 = y + 0.1 ym01 = y – 0.2 x = x, y = y, xp02 = x + 0.4, xp01 = x + 0.1, yp01 = y + 0.2, fig.quadratic(x0 = x, y0 = y, x1 = x + 0.4, y1 = y + 0.01, cx = x + 0.1, cy = y + 0.2, line_color = “blue”, line_width = 3) Output Print Page Previous Next Advertisements ”;
Bokeh – Area Plots
Bokeh – Area Plots ”; Previous Next Area plots are filled regions between two series that share a common index. Bokeh”s Figure class has two methods as follows − varea() Output of the varea() method is a vertical directed area that has one x coordinate array, and two y coordinate arrays, y1 and y2, which will be filled between. 1 x The x-coordinates for the points of the area. 2 y1 The y-coordinates for the points of one side of the area. 3 y2 The y-coordinates for the points of the other side of the area. Example from bokeh.plotting import figure, output_file, show fig = figure() x = [1, 2, 3, 4, 5] y1 = [2, 6, 4, 3, 5] y2 = [1, 4, 2, 2, 3] fig.varea(x = x,y1 = y1,y2 = y2) output_file(”area.html”) show(fig) Output harea() The harea() method on the other hand needs x1, x2 and y parameters. 1 x1 The x-coordinates for the points of one side of the area. 2 x2 The x-coordinates for the points of the other side of the area. 3 y The y-coordinates for the points of the area. Example from bokeh.plotting import figure, output_file, show fig = figure() y = [1, 2, 3, 4, 5] x1 = [2, 6, 4, 3, 5] x2 = [1, 4, 2, 2, 3] fig.harea(x1 = x1,x2 = x2,y = y) output_file(”area.html”) show(fig) Output Print Page Previous Next Advertisements ”;
Bokeh – Styling Visual Attributes ”; Previous Next The default appearance of a Bokeh plot can be customised by setting various properties to desired value. These properties are mainly of three types − Line properties Following table lists various properties related to line glyph. 1 line_color color is used to stroke lines with 2 line_width This is used in units of pixels as line stroke width 3 line_alpha Between 0 (transparent) and 1 (opaque) this acts as a floating point 4 line_join how to join together the path segments. Defined values are: ”miter” (miter_join), ”round” (round_join), ”bevel” (bevel_join) 5 line_cap how to terminate the path segments. Defined values are: ”butt” (butt_cap), ”round” (round_cap), ”square” (square_cap) 6 line_dash BThis is used for a line style. Defined values are: ”solid”, ”dashed”, ”dotted”, ”dotdash”, ”dashdot” 7 line_dash_offset The distance into the line_dash in pixels that the pattern should start from Fill properties Various fill properties are listed below − 1 fill_color This is used to fill paths with 2 fill_alpha Between 0 (transparent) and 1 (opaque), this acts as a floating point Text properties There are many text related properties as listed in the following table − 1 text_font font name, e.g., ”times”, ”helvetica” 2 text_font_size font size in px, em, or pt, e.g., ”12pt”, ”1.5em” 3 text_font_style font style to use ”normal” ”italic” ”bold” 4 text_color This is used to render text with 5 text_alpha Between 0 (transparent) and 1 (opaque), this is a floating point 6 text_align horizontal anchor point for text – ”left”, ”right”, ”center” 7 text_baseline vertical anchor point for text ”top”, ”middle”, ”bottom”, ”alphabetic”, ”hanging” Print Page Previous Next Advertisements ”;