Python - 使用 Bokeh 进行数据可视化


Bokeh 是一个用于 Web 浏览器的 Python 数据可视化库。它可以创建优雅、简洁的多功能图形。它用于快速轻松地创建交互式图表、仪表板和数据应用程序。在本文中,我们将了解如何使用 Bokeh 创建各种基本图形类型。

绘制线条

我们可以使用点坐标的 x 和 y 坐标作为两个列表来创建线形图。通过指定图形的高度和宽度,我们直接在浏览器中显示输出。我们还可以提供其他参数,例如线的宽度和线的颜色。

示例

from bokeh.io import show
from bokeh.plotting import figure
p = figure(plot_width=300, plot_height=300)
# add a line renderer
p.line([ 2, 1, 2, 4], [ 1, 3, 5, 4],
      line_width=2, color="blue")
# show the results
show(p)

输出

运行以上代码将得到以下结果:

绘制圆形

在此示例中,我们使用 circle() 函数以列表的形式为圆心的 x 和 y 坐标提供值。同样,我们可以将圆的颜色和大小作为参数提供给此函数。我们将结果输出到浏览器窗口。

示例

from bokeh.io import show
from bokeh.plotting import figure
p = figure(plot_width=400, plot_height=300)
# add a line renderer
p.circle([ 2, 1.5, 2, 3,2.4], [ 2, 3, 4, 4,3],
         size = 10, color = "red", alpha = 0.8)
# show the results
show(p)

输出

运行以上代码将得到以下结果:

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

绘制条形图

条形图是通过使用 vbar 函数绘制的。在下面的示例中,我们取一个值的列表,这些值是工作日的名称,然后将每个条形的值作为列表传递给名为 top 的参数。当然,使用更复杂的程序,我们可以从文件或 API 导入外部数据,并将这些值提供给这些参数。

示例

from bokeh.io import show
from bokeh.plotting import figure
sales_qty = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
# Set the x_range to the list of categories above
p = figure(x_range=sales_qty , plot_height=250, title="Sales Figures")
# Categorical values can also be used as coordinates
p.vbar(x=sales_qty , top=[6, 3, 4, 2, 4], width=0.4)
# Set some properties to make the plot look better
p.xgrid.grid_line_color = None
p.y_range.start = 0
show(p)

输出

运行以上代码将得到以下结果:

更新于: 2021-01-25

217 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告