背景
在 Bokeh 初探之后,學習使用它來做個圖
目標
做一個柱狀圖,支持多個 y 數據源,即有堆疊效果的柱狀圖 stacked bar
實現
單數據源 簡單的柱狀圖
參考 Handling Categorical Data — Bokeh 1.4.0 documentation
from bokeh.io import show, output_file
from bokeh.plotting import figure
output_file("bars.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]
p = figure(x_range=fruits, plot_height=250, title="Fruit Counts", toolbar_location=None, tools="")
p.vbar(x=fruits, top=counts, width=0.9)
p.xgrid.grid_line_color = None
p.y_range.start = 0
show(p)
效果圖見上述參考
增加一個 y 數據源,做堆疊效果
這樣的話,需要考慮:
- 數據源:不能是單一的列表了,得能容納多組數據。用字典。
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
data = {'fruits' : fruits,
'2015' : [2, 1, 4, 3, 2, 4],
'2016' : [5, 3, 4, 2, 4, 6],
'2017' : [3, 2, 4, 4, 5, 3]}
- 顏色:區分不同的數據源
colors = ["green", "#718dbf", "#e84d60","#e84d20","#e84361"]
配色是個問題,一不小心就會很丑,后面會提到用調色板 palette
- 畫圖:上面的
vbar
不支持堆疊
p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data,legend_label=years)
導出為文件
Exporting Plots — Bokeh 1.4.0 documentation
- html
output_file("file.html")
-
png
-
npm install selenium phantomjs
-
npm install -g phantomjs-prebuilt
-
pip install bokeh
然后 from bokeh.io import export_png
數據源: 從 .csv 文件讀取數據
我試過兩種方式,現在用的是第二種 pandas
- numpy 的
genfromtxt
但是我遇到很多問題,包括不同的 dtype參數,names參數等,返回不同的數據類型的 array,感覺很不方便(如排序等),所以后來棄用了,當然也是因為我不太熟。
from numpy import genfromtxt
my_data = genfromtxt("data.csv", delimiter=',', dtype=None, encoding="utf8")
- pandas
還是這個方便,讀取文件 :
df = pd.read_csv("data.csv",header=0)
取前 7 行:df = df.head(n=7)
取某一列:df['col1']
幾列求和: df['col1'] + df['col2'] + df['col3']
排序:df = df.sort_values(by='col1', ascending=False)
x axis 旋轉
Styling Visual Attributes — Bokeh 1.4.0 documentation
比如左斜 旋轉 45 度:
p.xaxis.major_label_orientation = 360-45
調色板
前面我們用 colors = ["green", "#718dbf", "#e84d60","#e84d20","#e84361"]
人工配色,會很丑不專業,bokeh 有自帶的調色板,倒是很方便,還好看。
>>> from bokeh.palettes import brewer
>>> colors = brewer["Blues"][6]
>>> colors
['#08519c', '#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#eff3ff']
具體列表參考:
- bokeh.palettes
- 源碼:bokeh/palettes.py at master · bokeh/bokeh
- bokeh.colors — Bokeh 1.4.0 documentation
分類數據處理
如果 x 數據只是數字 如[1,2,3]
,上面demo 中的 p.figure
足以處理
但如果 x 或 y 坐標是一些分類數據如["apple","orange"]
,則需要再添加 x_range
,或 y_range
等
如
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
p = figure(x_range=fruits, ... )
p.vbar(x=x, top=y, legend_label="Temp.", width=0.9)
參考 Handling Categorical Data — Bokeh 1.4.0 documentation