当前位置:   article > 正文

python bokeh_使用Bokeh在Python中进行交互式数据可视化

bokeh python callbacks

python bokeh

Bokeh prides itself on being a library for interactive data visualization.

Bokeh以成为交互式数据可视化的库而自豪。

Unlike popular counterparts in the Python visualization space, like Matplotlib and Seaborn, Bokeh renders its graphics using HTML and JavaScript. This makes it a great candidate for building web-based dashboards and applications. However, it’s an equally powerful tool for exploring and understanding your data or creating beautiful custom charts for a project or report.

与Python可视化领域的流行同行(例如Matplotlib和Seaborn)不同,Bokeh使用HTML和JavaScript渲染其图形。 这使其非常适合构建基于Web的仪表板和应用程序。 但是,它是用于浏览和理解数据或为项目或报告创建漂亮的自定义图表的功能同样强大的工具。

Using a number of examples on a real-world dataset, the goal of this tutorial is to get you up and running with Bokeh.

通过使用真实数据集上的许多示例,本教程的目标是使您开始使用Bokeh。

You’ll learn how to:

您将学习如何:

  • Transform your data into visualizations, using Bokeh
  • Customize and organize your visualizations
  • Add interactivity to your visualizations
  • 使用Bokeh 将数据转换为可视化
  • 自定义和组织可视化
  • 为可视化添加交互性

So let’s jump in.

因此,让我们进入。

Free Bonus: Click here to get access to a chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

免费红利: 单击此处可访问Python技巧的一章:该书通过简单的示例向您展示了Python的最佳实践,您可以立即应用这些示例编写更精美的Pythonic代码。

从数据到可视化 (From Data to Visualization)

Building a visualization with Bokeh involves the following steps:

使用Bokeh构建可视化过程涉及以下步骤:

  • Prepare the data
  • Determine where the visualization will be rendered
  • Set up the figure(s)
  • Connect to and draw your data
  • Organize the layout
  • Preview and save your beautiful data creation
  • 准备数据
  • 确定可视化将在哪里呈现
  • 设置数字
  • 连接并绘制数据
  • 整理布局
  • 预览并保存您创建的漂亮数据

Let’s explore each step in more detail.

让我们更详细地探索每个步骤。

准备数据 (Prepare the Data)

Any good data visualization starts with—you guessed it—data. If you need a quick refresher on handling data in Python, definitely check out the growing number of excellent Real Python tutorials on the subject.

任何好的数据可视化都始于(您猜对了)数据。 如果您需要快速处理Python中的数据,请一定要查看有关该主题越来越多的出色Real Python教程

This step commonly involves data handling libraries like Pandas and Numpy and is all about taking the required steps to transform it into a form that is best suited for your intended visualization.

此步骤通常涉及诸如PandasNumpy之类的数据处理库,并且全部涉及采取必要步骤将其转换为最适合您的预期可视化的形式。

确定可视化将在哪里渲染 (Determine Where the Visualization Will Be Rendered)

At this step, you’ll determine how you want to generate and ultimately view your visualization. In this tutorial, you’ll learn about two common options that Bokeh provides: generating a static HTML file and rendering your visualization inline in a Jupyter Notebook.

在这一步,您将确定如何生成并最终查看可视化效果。 在本教程中,您将了解Bokeh提供的两个常用选项:生成静态HTML文件以及在Jupyter Notebook中内嵌呈现可视化效果。

设置图 (Set up the Figure(s))

From here, you’ll assemble your figure, preparing the canvas for your visualization. In this step, you can customize everything from the titles to the tick marks. You can also set up a suite of tools that can enable various user interactions with your visualization.

在这里,您将组装图形,为可视化准备画布。 在此步骤中,您可以自定义从标题到刻度线的所有内容。 您还可以设置一套工具,以实现与可视化的各种用户交互。

连接并绘制数据 (Connect to and Draw Your Data)

Next, you’ll use Bokeh’s multitude of renderers to give shape to your data. Here, you have the flexibility to draw your data from scratch using the many available marker and shape options, all of which are easily customizable. This functionality gives you incredible creative freedom in representing your data.

接下来,您将使用Bokeh的大量渲染器来使数据成形。 在这里,您可以使用许多可用的标记和形状选项灵活地从头开始绘制数据,所有这些都可以轻松自定义。 此功能为您提供了令人难以置信的创作自由,可以代表您的数据。

Additionally, Bokeh has some built-in functionality for building things like stacked bar charts and plenty of examples for creating more advanced visualizations like network graphs and maps.

此外,Bokeh具有一些内置功能,可用于构建诸如堆积的条形图之类的东西,以及用于创建更高级的可视化效果(如网络图地图)的大量示例。

整理布局 (Organize the Layout)

If you need more than one figure to express your data, Bokeh’s got you covered. Not only does Bokeh offer the standard grid-like layout options, but it also allows you to easily organize your visualizations into a tabbed layout in just a few lines of code.

如果您需要一个以上的数字来表达您的数据,那么Bokeh就可以满足您的要求。 Bokeh不仅提供标准的类似于网格的布局选项,而且还使您可以轻松地用几行代码将可视化内容组织到选项卡式布局中。

In addition, your plots can be quickly linked together, so a selection on one will be reflected on any combination of the others.

此外,您的地块可以快速链接在一起,因此一个地块的选择将反映在其他地块的任何组合上。

预览并保存您创建的漂亮数据 (Preview and Save Your Beautiful Data Creation)

Finally, it’s time to see what you created.

最后,是时候看看您创建的内容了。

Whether you’re viewing your visualization in a browser or notebook, you’ll be able to explore your visualization, examine your customizations, and play with any interactions that were added.

无论您是在浏览器中还是在笔记本电脑中查看可视化,您都可以浏览可视化,检查自定义设置并进行添加的交互。

If you like what you see, you can save your visualization to an image file. Otherwise, you can revisit the steps above as needed to bring your data vision to reality.

如果您喜欢所看到的内容,则可以将可视化文件保存到图像文件中。 否则,您可以根据需要重新查看上述步骤,以实现数据愿景。

That’s it! Those six steps are the building blocks for a tidy, flexible template that can be used to take your data from the table to the big screen:

而已! 这六个步骤是一个整洁,灵活的模板的构建块,可用于将数据从表移至大屏幕:

  1. """Bokeh Visualization Template
  2. """Bokeh Visualization Template
  3. This template is a general outline for turning your data into a
  4. This template is a general outline for turning your data into a
  5. visualization using Bokeh.
  6. visualization using Bokeh.
  7. """
  8. """
  9. # Data handling
  10. # Data handling
  11. import import pandas pandas as as pd
  12. pd
  13. import import numpy numpy as as np
  14. np
  15. # Bokeh libraries
  16. # Bokeh libraries
  17. from from bokeh.io bokeh.io import import output_fileoutput_file , , output_notebook
  18. output_notebook
  19. from from bokeh.plotting bokeh.plotting import import figurefigure , , show
  20. show
  21. from from bokeh.models bokeh.models import import ColumnDataSource
  22. ColumnDataSource
  23. from from bokeh.layouts bokeh.layouts import import rowrow , , columncolumn , , gridplot
  24. gridplot
  25. from from bokeh.models.widgets bokeh.models.widgets import import TabsTabs , , Panel
  26. Panel
  27. # Prepare the data
  28. # Prepare the data
  29. # Determine where the visualization will be rendered
  30. # Determine where the visualization will be rendered
  31. output_fileoutput_file (( 'filename.html''filename.html' ) ) # Render to static HTML, or
  32. # Render to static HTML, or
  33. output_notebookoutput_notebook () () # Render inline in a Jupyter Notebook
  34. # Render inline in a Jupyter Notebook
  35. # Set up the figure(s)
  36. # Set up the figure(s)
  37. fig fig = = figurefigure () () # Instantiate a figure() object
  38. # Instantiate a figure() object
  39. # Connect to and draw the data
  40. # Connect to and draw the data
  41. # Organize the layout
  42. # Organize the layout
  43. # Preview and save
  44. # Preview and save
  45. showshow (( figfig ) ) # See what I made, and save if I like it
  46. # See what I made, and save if I like it

Some common code snippets that are found in each step are previewed above, and you’ll see how to fill out the rest as you move through the rest of the tutorial!

上面已预览了每个步骤中发现的一些常见代码段,在本教程的其余部分中,您将看到如何填写其余部分!

产生你的第一个数字 (Generating Your First Figure)

There are multiple ways to output your visualization in Bokeh. In this tutorial, you’ll see these two options:

多种方法可以在Bokeh中输出可视化效果 。 在本教程中,您将看到以下两个选项:

  • output_file('filename.html') will write the visualization to a static HTML file.
  • output_notebook() will render your visualization directly in a Jupyter Notebook.
  • output_file('filename.html')会将可视化内容写入静态HTML文件。
  • output_notebook()将直接在Jupyter Notebook中呈现可视化效果。

It’s important to note that neither function will actually show you the visualization. That doesn’t happen until show() is called. However, they will ensure that, when show() is called, the visualization appears where you intend it to.

重要的是要注意,这两个功能实际上都不会为您显示可视化效果。 在调用show()之前不会发生这种情况。 但是,它们将确保在调用show()时,可视化内容将显示在您想要的位置。

By calling both output_file() and output_notebook() in the same execution, the visualization will be rendered both to a static HTML file and inline in the notebook. However, if for whatever reason you run multiple output_file() commands in the same execution, only the last one will be used for rendering.

通过在同一执行中同时调用output_file()output_notebook() ,可视化文件将呈现为静态HTML文件并在笔记本中内联。 但是,如果出于某种原因在同一执行中运行多个output_file()命令,则仅使用最后一个命令进行渲染。

This is a great opportunity to give you your first glimpse at a default Bokeh figure() using output_file():

这是一个很好的机会,可以使用output_file()默认的Bokeh figure() output_file()

output_file()

As you can see, a new browser window opened with a tab called Empty Bokeh Figure and an empty figure. Not shown is the file generated with the name output_file_test.html in your current working directory.

如您所见,将打开一个新的浏览器窗口,其中包含一个名为Empty Bokeh Figure和一个空图的选项卡。 在当前工作目录中未显示名称为output_file_test.html的文件。

If you were to run the same code snippet with output_notebook() in place of output_file(), assuming you have a Jupyter Notebook fired up and ready to go, you will get the following:

如果要使用output_notebook()代替output_file()运行相同的代码段,并假设已启动Jupyter Notebook并准备就绪,则将获得以下内容:

  1. # Bokeh Libraries
  2. # Bokeh Libraries
  3. from from bokeh.io bokeh.io import import output_notebook
  4. output_notebook
  5. from from bokeh.plotting bokeh.plotting import import figurefigure , , show
  6. show
  7. # The figure will be right in my Jupyter Notebook
  8. # The figure will be right in my Jupyter Notebook
  9. output_notebookoutput_notebook ()
  10. ()
  11. # Set up a generic figure() object
  12. # Set up a generic figure() object
  13. fig fig = = figurefigure ()
  14. ()
  15. # See what it looks like
  16. # See what it looks like
  17. showshow (( figfig )
  18. )

output_notebook()

As you can see, the result is the same, just rendered in a different location.

如您所见,结果是相同的,只是在不同的位置呈现。

More information about both output_file() and output_notebook() can be found in the Bokeh official docs.

可以在Bokeh官方文档中找到有关output_file()output_notebook()更多信息。

Note: Sometimes, when rendering multiple visualizations sequentially, you’ll see that past renders are not being cleared with each execution. If you experience this, import and run the following between executions:

注意:有时,当顺序渲染多个可视化对象时,您会看到每次执行都不会清除过去的渲染。 如果遇到这种情况,请在两次执行之间导入并运行以下命令:

Before moving on, you may have noticed that the default Bokeh figure comes pre-loaded with a toolbar. This is an important sneak preview into the interactive elements of Bokeh that come right out of the box. You’ll find out more about the toolbar and how to configure it in the Adding Interaction section at the end of this tutorial.

在继续之前,您可能已经注意到默认的Bokeh图形已预装了工具栏。 这是开箱即用的Bokeh交互元素的重要预览。 您将在本教程结尾的“ 添加交互”部分中找到有关工具栏以及如何配置它的更多信息。

为数据做好准备 (Getting Your Figure Ready for Data)

Now that you know how to create and view a generic Bokeh figure either in a browser or Jupyter Notebook, it’s time to learn more about how to configure the figure() object.

既然您知道如何在浏览器或Jupyter Notebook中创建和查看通用的Bokeh人物,是时候了解有关如何配置fig figure()对象的更多信息了。

The figure() object is not only the foundation of your data visualization but also the object that unlocks all of Bokeh’s available tools for visualizing data. The Bokeh figure is a subclass of the Bokeh Plot object, which provides many of the parameters that make it possible to configure the aesthetic elements of your figure.

figure()对象不仅是数据可视化的基础,而且是解锁Bokeh可用的用于可视化数据的所有工具的对象。 散景图是“ 散景图”对象的子类,该对象提供许多参数,这些参数使您可以配置图形的美学元素。

To show you just a glimpse into the customization options available, let’s create the ugliest figure ever:

为了让您了解可用的自定义选项,让我们创建有史以来最丑陋的人物:

  1. # Bokeh Libraries
  2. # Bokeh Libraries
  3. from from bokeh.io bokeh.io import import output_notebook
  4. output_notebook
  5. from from bokeh.plotting bokeh.plotting import import figurefigure , , show
  6. show
  7. # The figure will be rendered inline in my Jupyter Notebook
  8. # The figure will be rendered inline in my Jupyter Notebook
  9. output_notebookoutput_notebook ()
  10. ()
  11. # Example figure
  12. # Example figure
  13. fig fig = = figurefigure (( background_fill_colorbackground_fill_color == 'gray''gray' ,
  14. ,
  15. background_fill_alphabackground_fill_alpha == 0.50.5 ,
  16. ,
  17. border_fill_colorborder_fill_color == 'blue''blue' ,
  18. ,
  19. border_fill_alphaborder_fill_alpha == 0.250.25 ,
  20. ,
  21. plot_heightplot_height == 300300 ,
  22. ,
  23. plot_widthplot_width == 500500 ,
  24. ,
  25. h_symmetryh_symmetry == TrueTrue ,
  26. ,
  27. x_axis_labelx_axis_label == 'X Label''X Label' ,
  28. ,
  29. x_axis_typex_axis_type == 'datetime''datetime' ,
  30. ,
  31. x_axis_locationx_axis_location == 'above''above' ,
  32. ,
  33. x_rangex_range == (( '2018-01-01''2018-01-01' , , '2018-06-30''2018-06-30' ),
  34. ),
  35. y_axis_labely_axis_label == 'Y Label''Y Label' ,
  36. ,
  37. y_axis_typey_axis_type == 'linear''linear' ,
  38. ,
  39. y_axis_locationy_axis_location == 'left''left' ,
  40. ,
  41. y_rangey_range == (( 00 , , 100100 ),
  42. ),
  43. titletitle == 'Example Figure''Example Figure' ,
  44. ,
  45. title_locationtitle_location == 'right''right' ,
  46. ,
  47. toolbar_locationtoolbar_location == 'below''below' ,
  48. ,
  49. toolstools == 'save''save' )
  50. )
  51. # See what it looks like
  52. # See what it looks like
  53. showshow (( figfig )
  54. )

示例图

Once the figure() object is instantiated, you can still configure it after the fact. Let’s say you want to get rid of the gridlines:

实例化fig figure()对象后,您仍然可以在配置之后进行配置。 假设您要摆脱网格线:

The gridline properties are accessible via the figure’s grid attribute. In this case, setting grid_line_color to None effectively removes the gridlines altogether. More details about figure attributes can be found below the fold in the Plot class documentation.

可通过图形的grid属性访问gridline属性。 在这种情况下,将grid_line_color设置为None可以完全删除网格线。 有关图形属性的更多详细信息,可以在Plot类文档的首屏下面找到。

Example Figure w/o Gridlines

Note: If you’re working in a notebook or IDE with auto-complete functionality, this feature can definitely be your friend! With so many customizable elements, it can be very helpful in discovering the available options:

注意:如果您使用的是具有自动完成功能的笔记本电脑或IDE,那么此功能绝对可以成为您的朋友! 有这么多可定制的元素,在发现可用选项时会非常有帮助:

Auto Complete GIF

Otherwise, doing a quick web search, with the keyword bokeh and what you are trying to do, will generally point you in the right direction.

否则,使用关键字bokeh和您要尝试的操作进行快速的网络搜索通常会为您指明正确的方向。

There is tons more I could touch on here, but don’t feel like you’re missing out. I’ll make sure to introduce different figure tweaks as the tutorial progresses. Here are some other helpful links on the topic:

在这里,我还有很多其他可以触及的地方,但不要觉得您错过了。 随着教程的进行,我将确保引入不同的图形调整。 这是有关此主题的其他一些有用的链接:

  • The Bokeh Plot Class is the superclass of the figure() object, from which figures inherit a lot of their attributes.
  • The Figure Class documentation is a good place to find more detail about the arguments of the figure() object.
  • 散景图类fig figure()对象的超类, figure()从中继承许多属性。
  • Figure Class文档是查找关于figure()对象的参数的更多详细信息的好地方。

Here are a few specific customization options worth checking out:

以下是一些值得一试的自定义选项:

  • Text Properties covers all the attributes related to changing font styles, sizes, colors, and so forth.
  • TickFormatters are built-in objects specifically for formatting your axes using Python-like string formatting syntax.
  • 文本属性涵盖与更改字体样式,大小,颜色等有关的所有属性。
  • TickFormatters是内置对象,专门用于使用类似Python的字符串格式语法来格式化轴。

Sometimes, it isn’t clear how your figure needs to be customized until it actually has some data visualized in it, so next you’ll learn how to make that happen.

有时,在实际显示一些数据之前,还不清楚如何对您的图形进行自定义,因此接下来您将学习如何实现这一目标。

使用字形绘制数据 (Drawing Data With Glyphs)

An empty figure isn’t all that exciting, so let’s look at glyphs: the building blocks of Bokeh visualizations. A glyph is a vectorized graphical shape or marker that is used to represent your data, like a circle or square. More examples can be found in the

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/682073
推荐阅读
相关标签
  

闽ICP备14008679号