Python Bokeh 入門


為了滿足日益增長的需求,Python 提供了許多用於資料視覺化的模組。Bokeh 因其建立引人入勝和互動式資料故事的能力而脫穎而出。本文將介紹 Bokeh,詳細說明如何安裝它,列出其功能,並深入探討實際應用,以突出其強大的可能性。

瞭解 Bokeh

Bokeh 是一個 Python 包,它簡化了建立可縮放的互動式視覺化效果,可在 Web 瀏覽器中使用。由於其適應性,Bokeh 成為工程、金融和資料科學等各個行業的有效工具。

安裝 Bokeh

如果您的 Python 環境尚未安裝 Bokeh,您可以使用 pip 命令安裝它。

pip install bokeh

Bokeh 實踐:實際示例

為了更好地理解如何使用 Bokeh 建立互動式圖表,讓我們深入探討一些實際示例。

示例 1:建立簡單的折線圖

在 Bokeh 中,可以使用 figure 函式和 line 方法建立簡單的折線圖。這是一個示例。

from bokeh.plotting import figure, show

# Sample data
x = [1, 2, 3, 4, 5]
y = [6, 7, 2, 3, 6]

# Create a new plot
p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')

# Add a line renderer
p.line(x, y, legend_label="Temp.", line_width=2)

# Show the result
show(p)

示例 2:使用 Bokeh 建立散點圖

此外,Bokeh 還提供了一種簡單的建立散點圖的方法。以下是操作方法。

from bokeh.plotting import figure, show
from bokeh.models import HoverTool

# Sample data
x = [1, 2, 3, 4, 5]
y = [6, 7, 8, 7, 3]

# Create a new plot
p = figure(title="simple scatter plot example", x_axis_label='x', y_axis_label='y', tools="hover,pan,reset,wheel_zoom")

# Add hover tool
hover = p.select(dict(type=HoverTool))
hover.tooltips = [("Index", "$index"), ("(x,y)", "($x, $y)"),]

# Add a circle renderer
p.circle(x, y, size=10, alpha=0.5)

# Show the result
show(p)

此示例包含 Bokeh 提供的眾多互動式工具之一:HoverTool。

示例 3:使用 Bokeh 建立條形圖

Bokeh 可以建立條形圖和其他不同型別的圖。這是一個簡單的示例。

from bokeh.plotting import figure, show
from bokeh.io import output_file
from bokeh.models import ColumnDataSource

# Prepare some data
data = {'fruits': ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'], 'counts': [5, 3, 4, 2, 4, 6]}
source = ColumnDataSource(data=data)

# Create a new plot
p = figure(x_range=data['fruits'], plot_height=250, toolbar_location=None, title="Fruit Counts")

# Add a bar renderer
p.vbar(x='fruits', top='counts', width=0.9, source=source, legend_label="fruits")

# Customize the plot
p.xgrid.grid_line_color = None
p.y_range.start = 0
p.y_range.end = 9
p.legend.orientation = "horizontal"
p.legend.location = "top_center"

# Show the result
show(p)

在這個示例中,我們建立了一個簡單的垂直條形圖,以顯示不同水果的數量。x 軸表示水果型別,y 軸表示水果數量。使用 Bokeh 的 ColumnDataSource 簡化了在多個繪圖和部件之間傳輸資料。

結論

在 Python 生態系統中,Bokeh 是構建複雜互動式視覺化的重要工具。資料分析師和科學家們都欣賞它處理大型資料集並建立高質量視覺化的能力。

此頁面提供了 Bokeh 的基本概述,但它只是觸及了其可能性。Bokeh 還提供許多其他功能,例如流式資料、不同區域的地圖,以及使用 Bokeh 伺服器構建完全互動式資料應用程式的能力。

學習 Bokeh 為強大的資料敘事和展示打開了大門。與任何工具一樣,實踐和嘗試不同的繪圖型別以及 Bokeh 的互動式功能是有效學習如何使用它的最佳方法。

更新於:2023年7月17日

瀏覽量:173

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告