[Data Science] Bokeh [Use Bokeh drawing, data, drawing, renderer and custom visualization, output and export, display or save graphics]


1. Drawing using Bokeh

  Bokeh is an interactive visual library for Python forGenerate high-performance visualizations of large-scale data sets for display in the browser.
Insert image description here
  The common bokeh.plotting interface of Bokeh's middle layer mainly consists of two components: data and icons .
Insert image description here
  The basic steps for drawing using the bokeh.plotting interface are:
  1. Prepare data .
  Python list, Numpy array, Pandas data frame or other sequence value
  2. Prepare data to create graphics.
  3. Add a renderer to the data and customize the visualization chart .
  4. Specify the type of output generated .
  5. Display the view or save the results .

>>> from bokeh.plotting import figure
>>> from bokeh.io import output_file, show
>>> x = [1, 2, 3, 4, 5]
>>> y = [6, 7, 2, 4, 5]
>>> p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')
>>> p.line(x, y, legend="Temp.", line_width=2)
>>> output_file("lines.html")
>>> show(p)

2. Data

  Typically, Bokeh converts the data to a column data source behind the scenes , but it can alsoManual conversion

>>> import numpy as np
>>> import pandas as pd
# 首先需要导入必要的库(NumPy和Pandas)
>>> df = pd.DataFrame(np.array([[33.9,4,65, 'US'],[32.4,4,66, 'Asia'],[21.4,4,109, 'Europe']]), columns=['mpg','cyl', 'hp', 'origin'],index=['Toyota', 'Fiat', 'Volvo'])
>>> from bokeh.models import ColumnDataSource
# 然后创建一个包含数据的数据框(DataFrame)
>>> cds_df = ColumnDataSource(df)
# 通过将数据框传递给ColumnDataSource函数,将数据框转换为列数据源对象

  Above we use NumPy and PandasCreated a dataframe containing car related data. Then, convert the data frame into a column data source object cds_df by passing the data frame to the ColumnDataSource function . You can now use this column data source object to create a Bokeh visualization andUse it with other Bokeh components like charts, graphs, etc.


3. Drawing

  First use Bokeh to create three graphic objects .

>>> from bokeh.plotting import figure
>>> p1 = figure(plot_width=300,tools='pan,box_zoom')
>>> p2 = figure(plot_width=300, plot_height=300, x_range=(0, 8), y_range=(0, 8))
>>> p3 = figure() 

  Through these graphic objects, we canOther functions and methods using Bokeh Add data, chart types , and more, and visualize the data .


4. Renderer and custom visualization

4.1 Icons

4.1.1 Scatter markers

  Using Bokeh to Graph ObjectsAdd scatter plots and square plots

>>> p1.circle(np.array([1,2,3]), np.array([3,2,1]), fill_color='white')
>>> p2.square(np.array([1.5,3.5,5.5]), [1,4,3], 

Insert image description here


4.1.2 Line icons

  Using Bokeh to Graph ObjectsAdd line graph

>>> p1.line([1,2,3,4], [3,4,5,6], line_width=2)
# 使用p1.line()函数将一条直线段添加到图形中。这里传入的参数为x坐标和y坐标的数组:[1,2,3,4]和[3,4,5,6]
# 通过设置line_width=2,将线段的宽度设置为2个像素
>>> p2.multi_line(pd.DataFrame([[1,2,3],[5,6,7]]),pd.DataFrame([[3,4,5],[3,2,1]]),color="blue")
# 使用p2.multi_line()函数将多条线段组成的线段图添加到图形中。这里传入的参数为两个DataFrame对象:第一个DataFrame对象包含x坐标的数据,第二个DataFrame对象包含y坐标的数据
# x坐标的DataFrame为pd.DataFrame([[1,2,3],[5,6,7]]),y坐标的DataFrame为pd.DataFrame([[3,4,5],[3,2,1]])。通过设置color="blue",将线段的颜色设置为蓝色

Insert image description here


4.2 Custom icons

4.2.1 Icon selection and inversion

  Create a graph object using Bokeh and add a scatter plot to the graph

>>> p = figure(tools='box_select')
>>> p.circle('mpg', 'cyl', source=cds_df, selection_color='red', nonselection_alpha=0.1)

  Above we create a graphic object with a marquee selection tool and add a scatter plot to the graphic . The x-coordinate of the scatter plot is mpg and the y-coordinate is cyl. The data source of the scatter plot is the ColumnDataSource object named cds_df . The color of selected scatter points is red, and the transparency of unselected scatter points is 0.1.
Insert image description here


4.2.2 Inside the drawing area

  Add a hover tool to a graphics object using Bokeh

>>> from bokeh.models import HoverTool
# 首先,从 bokeh.models 模块导入 HoverTool 类
>>> hover = HoverTool(tooltips=None, mode='vline') 
# 使用 HoverTool() 函数创建一个悬停工具对象,并将其赋值给变量 hover
# 通过设置 tooltips=None 将工具提示设置为空,即不显示任何工具提示信息。通过设置 mode='vline' 将悬停模式设置为垂直线模式
>>>> p3.add_tools(hover)
# 使用 add_tools() 方法将悬停工具添加到图形对象 p3 中

  By executing the above code, we will create a hover tool object and add it to the graphics object p3 .Hover tools will display in vertical line mode and no tooltip information will be displayed
Insert image description here


4.2.3 Color table

>>> from bokeh.models import CategoricalColorMapper
>>> color_mapper = CategoricalColorMapper(factors=['US', 'Asia', 'Europe'],palette=['blue', 'red', 'green'])
>>> p3.circle('mpg', 'cyl', source=cds_df,color=dict(field='origin', transform=color_mapper),legend='Origin')

  By executing the above code, theCreate a scatter plot and use CategoricalColorMapper to map different categories of data points to different colors. The color map maps based on the value of the ' origin ' field and uses a legend to display each category.
Insert image description here


4.3 Legend location

4.3.1 Inside the drawing area

>>> p.legend.location = 'bottom_left'

4.3.2 Outside the drawing area

>>> from bokeh.models import Legend
>>> r1 = p2.asterisk(np.array([1,2,3]), np.array([3,2,1])
>>> r2 = p2.line([1,2,3,4], [3,4,5,6])
>>> legend = Legend(items=[("One" ,[p1, r1]),("Two",[r2])], 
 location=(0, -30))
>>> p.add_layout(legend, 'right')

4.4 Legend direction

>>> p.legend.orientation = "horizontal"
>>> p.legend.orientation = "vertical"

4.5 Legend background and border

>>> p.legend.border_line_color = "navy"
>>> p.legend.background_fill_color = "white"

4.6 Row and column layout

4.6.1 Line

>>> from bokeh.layouts import row
>>> layout = row(p1,p2,p3)

4.6.2 Column

>>> from bokeh.layouts import columns
>>> layout = column(p1,p2,p3)

4.6.3 Nesting of rows and columns

>>>layout = row(column(p1,p2), p3)

4.7 Grid layout

>>> from bokeh.layouts import gridplot
>>> row1 = [p1,p2]
>>> row2 = [p3]
>>> layout = gridplot([[p1,p2],[p3]])

4.8 Label layout

>>> from bokeh.models.widgets import Panel, Tabs
>>> tab1 = Panel(child=p1, title="tab1")
>>> tab2 = Panel(child=p2, title="tab2")
>>> layout = Tabs(tabs=[tab1, tab2])

4.9 Link diagram

4.9.1 Link axes

>>> p2.x_range = p1.x_range
>>> p2.y_range = p1.y_range

4.9.2 Link Brushing

>>> p4 = figure(plot_width = 100, tools='box_select,lasso_select')
>>> p4.circle('mpg', 'cyl', source=cds_df)
>>> p5 = figure(plot_width = 200, tools='box_select,lasso_select')
>>> p5.circle('mpg', 'hp', source=cds_df)
>>> layout = row(p4,p5)

5. Output and Export

5.1 Notebook

  Use Bokeh for output in Jupyter Notebook.

>>> from bokeh.io import output_notebook, show
# 从 bokeh.io 模块导入 output_notebook 和 show 函数
>>> output_notebook()
# 用 output_notebook() 函数将 Bokeh 的输出设置为在 Jupyter Notebook 中显示。这样可以确保图形将直接嵌入到笔记本中,并且可以在笔记本中进行交互和查看

  Bokeh graphics will be displayed embedded in the Jupyter Notebook and can be interacted with and viewed in the notebook .


5.2 HTML

5.2.1 Offline HTML

  Use Bokeh'sfile_html function Convert graphics to HTML files .

>>> from bokeh.embed import file_html
>>> from bokeh.resources import CDN 
>>> html = file_html(p, CDN, "my_plot")

  By executing the above code, the p graphics object will be converted into a string containing HTML code. This HTML code can be saved to a file or integrated into a web page to display and interact with Bokeh graphics .

>>> from bokeh.io import output_file, show
>>> output_file('my_bar_chart.html', mode='cdn')

5.2.2 Components

  Use Bokeh'scomponents function Convert graphics to JavaScript and HTML delimiters .

>>> from bokeh.embed import components
>>> script, div = components(p)

5.3 PNG

  Use Bokeh'sexport_png function Save the graphic as an image file in PNG format .

>>> from bokeh.io import export_png
>>> export_png(p, filename="plot.png")

  Graphical object p will be saved as a PNG image file named "plot.png". The file will be saved in the current working directory or the specified path. The location and name of the save can be changed by specifying a different file name and path .


5.4 SVG

  Use Bokeh'sexport_svgs function Save the graphic as a vector file in SVG format .

>>> from bokeh.io import export_svgs
>>> p.output_backend = "svg"
>>> export_svgs(p, filename="plot.svg")

  Graphic object p will be saved as a vector file in SVG format named "plot.svg". The file will be saved in the current working directory or the specified path. The location and name of the save can be changed by specifying a different file name and path. If the graphic is very complex, multiple SVG files may be generated.


6. Display or save graphics

  You can use Bokeh'sshow functionandsave functionTo display and save graphic objects p1 and layout .

>>> show(p1) >>> show(layout) 
>>> save(p1) >>> save(layout)

Guess you like

Origin blog.csdn.net/m0_65748531/article/details/132844405