bokeh


一  基本操作

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline

# 在notebook中創建繪圖空間

from bokeh.plotting import figure,show,output_file
# 導入圖表繪制、圖標展示模塊

from bokeh.io import output_notebook
# 導入notebook繪圖模塊

#output_notebook()
# notebook繪圖命令

#output_file("line.html")
# notebook繪圖命令,創建html文件
# 運行后會彈出html窗口

p = figure(plot_width=400, plot_height=400)   # 創建圖表,設置寬度、高度
p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
# 創建一個圓形散點圖

show(p)
# 繪圖




# 創建圖表工具 
# figure()

df = pd.DataFrame(np.random.randn(100,2),columns = ['A','B'])
# 創建數據

p = figure(plot_width=600, plot_height=400,    # 圖表寬度、高度
           tools = 'pan,wheel_zoom,box_zoom,save,reset,help',  # 設置工具欄,默認全部顯示
           toolbar_location='above',     # 工具欄位置:"above""below""left""right"
           x_axis_label = 'A', y_axis_label = 'B',    # X,Y軸label
           x_range = [-3,3], y_range = [-3,3],        # X,Y軸范圍
           title="測試圖表"                       # 設置圖表title
          )
# figure創建圖表,設置基本參數
# tool參考文檔:https://bokeh.pydata.org/en/latest/docs/user_guide/tools.html

p.title.text_color = "white"
p.title.text_font = "times"
p.title.text_font_style = "italic"
p.title.background_fill_color = "black"
# 設置標題:顏色、字體、風格、背景顏色

p.circle(df['A'], df['B'], size=20,  alpha=0.5)
show(p)






# 創建散點圖
# 這里.circle()是figure的一個繪圖方法

# 顏色設置

p = figure(plot_width=600, plot_height=400)
# 創建繪圖空間

p.circle(df.index, df['A'], color = 'green', size=10,  alpha=0.5)
p.circle(df.index, df['B'], color = '#FF0000', size=10,  alpha=0.5)
show(p)





# 顏色設置
# ① 147個CSS顏色,參考網址:http://www.colors.commutercreative.com/grid/
# ② RGB顏色值,參考網址:https://coolors.co/87f1ff-c0f5fa-bd8b9c-af125a-582b11

# 圖表邊框線參數設置

p = figure(plot_width=600, plot_height=400)
p.circle(df.index, df['A'], color = 'green', size=10,  alpha=0.5)
p.circle(df.index, df['B'], color = '#FF0000', size=10,  alpha=0.5)
# 繪制散點圖
 
p.outline_line_width = 7         # 邊框線寬
p.outline_line_alpha = 0.3       # 邊框線透明度
p.outline_line_color = "navy"    # 邊框線顏色
# 設置圖表邊框

show(p)





# 設置繪圖空間背景

p = figure(plot_width=600, plot_height=400)
p.circle(df.index, df['A'], color = 'green', size=10,  alpha=0.5)
p.circle(df.index, df['B'], color = '#FF0000', size=10,  alpha=0.5)
# 繪制散點圖

p.background_fill_color = "beige"    # 繪圖空間背景顏色
p.background_fill_alpha = 0.5        # 繪圖空間背景透明度
# 背景設置參數

show(p)





# 設置外邊界背景

p = figure(plot_width=600, plot_height=400)
p.circle(df.index, df['A'], color = 'green', size=10,  alpha=0.5)
p.circle(df.index, df['B'], color = '#FF0000', size=10,  alpha=0.5)
# 繪制散點圖

p.border_fill_color = "whitesmoke"    # 外邊界背景顏色
p.min_border_left = 80                # 外邊界背景 - 左邊寬度
p.min_border_right = 80               # 外邊界背景 - 右邊寬度
p.min_border_top = 10                 # 外邊界背景 - 上寬度
p.min_border_bottom = 10              # 外邊界背景 - 下寬度

show(p)





# Axes - 軸線設置
# 軸線標簽、軸線線寬、軸線顏色
# 字體顏色、字體角度

p = figure(plot_width=400, plot_height=400)
p.circle([1,2,3,4,5], [2,5,8,2,7], size=10)
# 繪制圖表

p.xaxis.axis_label = "Temp"
p.xaxis.axis_line_width = 3
p.xaxis.axis_line_color = "red"
# 設置x軸線:標簽、線寬、軸線顏色

p.yaxis.axis_label = "Pressure"
p.yaxis.major_label_text_color = "orange"
p.yaxis.major_label_orientation = "vertical"
# 設置y軸線:標簽、字體顏色、字體角度

p.axis.minor_tick_in = 5      # 刻度往繪圖區域內延伸長度
p.axis.minor_tick_out = 3   # 刻度往繪圖區域外延伸長度
# 設置刻度

p.xaxis.bounds = (2, 4)
# 設置軸線范圍

show(p)






# Axes - 軸線設置
# 標簽設置

p = figure(plot_width=400, plot_height=400)
p.circle([1,2,3,4,5], [2,5,8,2,7], size=10)

p.xaxis.axis_label = "Lot Number"
p.xaxis.axis_label_text_color = "#aa6666"
p.xaxis.axis_label_standoff = 30
# 設置標簽名稱、字體顏色、偏移距離

p.yaxis.axis_label = "Bin Count"
p.yaxis.axis_label_text_font_style = "italic"
# 設置標簽名稱、字體

show(p)







# Grid - 格網設置
# 線型設置

p = figure(plot_width=600, plot_height=400)
p.circle(df.index, df['A'], color = 'green', size=10,  alpha=0.5)
p.circle(df.index, df['B'], color = '#FF0000', size=10,  alpha=0.5)
# 繪制散點圖

p.xgrid.grid_line_color = None
# 顏色設置,None時則不顯示

p.ygrid.grid_line_alpha = 0.8
p.ygrid.grid_line_dash = [6, 4]
# 設置透明度,虛線設置
# dash → 通過設置間隔來做虛線

p.xgrid.minor_grid_line_color = 'navy'
p.xgrid.minor_grid_line_alpha = 0.1
# minor_line → 設置次軸線

show(p)




# Grid - 格網設置
# 顏色填充

p = figure(plot_width=600, plot_height=400)
p.circle(df.index, df['A'], color = 'green', size=10,  alpha=0.5)
p.circle(df.index, df['B'], color = '#FF0000', size=10,  alpha=0.5)
# 繪制散點圖

p.xgrid.grid_line_color = None
# 設置顏色為空

p.ygrid.band_fill_alpha = 0.1
p.ygrid.band_fill_color = "navy"
# 設置顏色填充,及透明度

#p.grid.bounds = (-1, 1)
# 設置填充邊界

show(p)






# Legend - 圖例設置
# 設置方法 → 在繪圖時設置圖例名稱 + 設置圖例位置

p = figure(plot_width=600, plot_height=400)
# 創建圖表

x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
# 設置x,y

p.circle(x, y, legend="sin(x)")
p.line(x, y, legend="sin(x)")
# 繪制line1,設置圖例名稱

p.line(x, 2*y, legend="2*sin(x)",line_dash=[4, 4], line_color="orange", line_width=2)
# 繪制line2,設置圖例名稱

p.square(x, 3*y, legend="3*sin(x)", fill_color=None, line_color="green")
p.line(x, 3*y, legend="3*sin(x)", line_color="green")
# 繪制line3,設置圖例名稱

p.legend.location = "bottom_left"
# 設置圖例位置:"top_left""top_center""top_right" (the default)、"center_right""bottom_right""bottom_center"
# "bottom_left""center_left""center"

p.legend.orientation = "vertical"
# 設置圖例排列方向:"vertical" (默認)or "horizontal"

p.legend.label_text_font = "times"
p.legend.label_text_font_style = "italic"  # 斜體
p.legend.label_text_color = "navy"
p.legend.label_text_font_size = '12pt'
# 設置圖例:字體、風格、顏色、字體大小

p.legend.border_line_width = 3
p.legend.border_line_color = "navy"
p.legend.border_line_alpha = 0.5
# 設置圖例外邊線:寬度、顏色、透明度

p.legend.background_fill_color = "gray"
p.legend.background_fill_alpha = 0.2
# 設置圖例背景:顏色、透明度

show(p)





總結一下:
Line Properties → 線設置
Fill Properties → 填充設置
Text Properties → 字體設置

1、Line Properties → 線設置
(1)line_color,設置顏色
(2)line_width,設置寬度
(3)line_alpha,設置透明度
(4)line_join,設置連接點樣式:'miter' miter_join,'round' round_join,'bevel' bevel_join
(5)line_cap,設置線端口樣式,'butt' butt_cap,'round' round_cap,'square' square_cap
(6)line_dash,設置線條樣式,'solid''dashed''dotted''dotdash''dashdot',或者整型數組方式(例如[6,4])

2、Fill Properties → 填充設置
(1)fill_color,設置填充顏色
(2)fill_alpha,設置填充透明度

3、Text Properties → 字體設置
(1)text_font,字體
(2)text_font_size,字體大小,單位為pt或者em( '12pt', '1.5em')
(3)text_font_style,字體風格,'normal' normal text,'italic' italic text,'bold' bold text
(4)text_color,字體顏色
(5)text_alpha,字體透明度
(6)text_align,字體水平方向位置,'left', 'right', 'center'7)text_baseline,字體垂直方向位置,'top''middle''bottom''alphabetic''hanging'

4、可見性
p.xaxis.visible = False
p.xgrid.visible = False
基本參數中都含有.visible參數,設置是否可見

 

二 圖標輔助參數設置

  

課程5.3】  圖表輔助參數設置

輔助標注、注釋、矢量箭頭

參考官方文檔:https://bokeh.pydata.org/en/latest/docs/user_guide/annotations.html#color-bars

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline

import warnings
warnings.filterwarnings('ignore') 
# 不發出警告

from bokeh.io import output_notebook
output_notebook()
# 導入notebook繪圖模塊

from bokeh.plotting import figure,show
# 導入圖表繪制、圖標展示模塊



# 輔助標注 -from bokeh.models.annotations import Span
# 導入Span模塊

x = np.linspace(0, 20, 200)
y = np.sin(x)
# 創建x,y數據

p = figure(y_range=(-2, 2))
p.line(x, y)
# 繪制曲線

upper = Span(location=1,           # 設置位置,對應坐標值
             dimension='width',    # 設置方向,width為橫向,height為縱向  
             line_color='olive', line_width=4   # 設置線顏色、線寬
            )
p.add_layout(upper)
# 繪制輔助線1

lower = Span(location=-1, dimension='width', line_color='firebrick', line_width=4)
p.add_layout(lower)
# 繪制輔助線2

show(p)




# 輔助標注 - 矩形

from bokeh.models.annotations import BoxAnnotation
# 導入BoxAnnotation模塊

x = np.linspace(0, 20, 200)
y = np.sin(x)
# 創建x,y數據

p = figure(y_range=(-2, 2))
p.line(x, y)
# 繪制曲線

upper = BoxAnnotation(bottom=1, fill_alpha=0.1, fill_color='olive')
p.add_layout(upper)
# 繪制輔助矩形1

lower = BoxAnnotation(top=-1, fill_alpha=0.1, fill_color='firebrick')
p.add_layout(lower)
# 繪制輔助矩形2

center = BoxAnnotation(top=0.6, bottom=-0.3, left=7, right=12,  # 設置矩形四邊位置
                       fill_alpha=0.1, fill_color='navy'        # 設置透明度、顏色
                      )
p.add_layout(center)
# 繪制輔助矩形3

show(p)




# 繪圖注釋

from bokeh.models.annotations import Label
# 導入Label模塊,注意是annotations中的Label

p = figure(x_range=(0,10), y_range=(0,10))
p.circle([2, 5, 8], [4, 7, 6], color="olive", size=10)
# 繪制散點圖

label = Label(x=5, y=7,       # 標注注釋位置
              x_offset=12,    # x偏移,同理y_offset
              text="Second Point",      # 注釋內容
              text_font_size="12pt",    # 字體大小
              border_line_color="red", background_fill_color="gray", background_fill_alpha = 0.5   # 背景線條顏色、背景顏色、透明度
             )
p.add_layout(label)
# 繪制注釋

show(p)



# 注釋箭頭

from bokeh.models.annotations import Arrow
from bokeh.models.arrow_heads import OpenHead, NormalHead, VeeHead   # 三種箭頭類型
# 導入相關模塊

p = figure(plot_width=600, plot_height=600)
p.circle(x=[0, 1, 0.5], y=[0, 0, 0.7], radius=0.1, color=["navy", "yellow", "red"], fill_alpha=0.1)
# 創建散點圖

p.add_layout(Arrow(end=OpenHead(line_color="firebrick", line_width=4),  # 設置箭頭類型,及相關參數:OpenHead, NormalHead, VeeHead
                   x_start=0, y_start=0, x_end=1, y_end=0))   # 設置箭頭矢量方向
# 繪制箭頭1

p.add_layout(Arrow(end=NormalHead(fill_color="orange"),
                   x_start=1, y_start=0, x_end=0.5, y_end=0.7))
# 繪制箭頭2

p.add_layout(Arrow(end=VeeHead(size=35), line_color="red",
                   x_start=0.5, y_start=0.7, x_end=0, y_end=0))
# 繪制箭頭3

show(p)




# 調色盤
# 顏色參考文檔:http://bokeh.pydata.org/en/latest/docs/reference/palettes.html
# ColorBrewer:http://colorbrewer2.org/#type=sequential&scheme=BuGn&n=3

import bokeh.palettes as bp
from bokeh.palettes import brewer

print('所有調色板名稱:\n',bp.__palettes__)
print('-------')
# 查看所有調色板名稱

print('藍色調色盤顏色:\n',bp.Blues)
print('-------')
# 查看藍色調色盤顏色

n = 8
colori = brewer['YlGn'][n]   
print('YlGn調色盤解析為%i個顏色,分別為:\n' % n, colori)
# 調色盤解析 → 不同顏色解析最多顏色有限

 

 

三  散點圖

  

s = pd.Series(np.random.randn(80))
# 創建數據

p = figure(plot_width=600, plot_height=400)
p.circle(s.index, s.values,                  # x,y值,也可以寫成:x=s.index, y = s.values
         size=25, color="navy", alpha=0.5,   # 點的大小、顏色、透明度(注意,這里的color是線+填充的顏色,同時線和填充可以分別上色,參數如下)
         fill_color = 'red',fill_alpha = 0.6, # 填充的顏色、透明度
         line_color = 'black',line_alpha = 0.8,line_dash = 'dashed',line_width = 2,   # 點邊線的顏色、透明度、虛線、寬度
         # 同時還有line_cap、line_dash_offset、line_join參數    
         legend = 'scatter-circle',    # 設置圖例
         #radius = 2   # 設置點的半徑,和size只能同時選一個
        )
# 創建散點圖,基本參數
# bokeh對line和fill是同樣的設置方法

p.legend.location = "bottom_right"
# 設置圖例位置

show(p)

 

 

# 2、散點圖不同 顏色上色/散點大小 的方法
# ① 數據中有一列專門用於設置顏色 / 點大小

from bokeh.palettes import brewer

rng = np.random.RandomState(1)
df = pd.DataFrame(rng.randn(100,2)*100,columns = ['A','B'])
# 創建數據,有2列隨機值

df['size'] = rng.randint(10,30,100)   
# 設置點大小字段

colormap1 = {1: 'red', 2: 'green', 3: 'blue'}    
df['color1'] = [colormap1[x] for x in rng.randint(1,4,100)]           # 調色盤1
print(df)
n = 8
colormap2 = brewer['Blues'][n]
df['color2'] = [colormap2[x] for x in rng.randint(0,n,100)]           # 調色盤2
# 設置顏色字段
# 通過字典/列表,識別顏色str
# 這里設置了兩個調色盤,第二個為藍色漸變

p = figure(plot_width=600, plot_height=400)
p.circle(df['A'], df['B'],       # 設置散點圖x,y值
         line_color = 'white',   # 設置點邊線為白色
         fill_color = df['color2'],fill_alpha = 0.5,   # 設置內部填充顏色,這里用到了顏色字段
         size = df['size']       # 設置點大小,這里用到了點大小字段
        )

show(p)

  這個感覺沒什么用啊,這顏色就是 隨機出來的 呀

 

 

# 2、散點圖不同 顏色上色/散點大小 的方法
# ② 遍歷數據分開做圖

rng = np.random.RandomState(1)
df = pd.DataFrame(rng.randn(100,2)*100,columns = ['A','B'])
df['type'] = rng.randint(0,7,100)
print(df.head())
# 創建數據

colors = ["red", "olive", "darkred", "goldenrod", "skyblue", "orange", "salmon"]
# 創建顏色列表

p = figure(plot_width=600, plot_height=400,tools = "pan,wheel_zoom,box_select,lasso_select,reset")
for t in df['type'].unique():
    p.circle(df['A'][df['type'] == t], df['B'][df['type'] == t],       # 設置散點圖x,y值 。這里對布爾型索引理解的還不夠深,應用還不夠熟練。!!
             size = 20,alpha = 0.5,
             color = colors[t])        
# 通過分類設置顏色

show(p)

  這個感覺應用場景比較多,因為按照類別分類很常見。

 

 

 

 

 

# 3、不同符號的散點圖
# asterisk(), circle(), circle_cross(), circle_x(), cross(), diamond(), diamond_cross(), inverted_triangle()
# square(), square_cross(), square_x(), triangle(), x()

p = figure(plot_width=600, plot_height=400,x_range = [0,3], y_range = [0,7])

p.circle_cross(1, 1, size = 30, alpha = 0.5, legend = 'circle_cross')
p.asterisk(1, 2, size = 30, alpha = 0.5, legend = 'asterisk')
p.circle_x(1, 3, size = 30, alpha = 0.5, legend = 'circle_x')
p.cross(1, 4, size = 30, alpha = 0.5, legend = 'cross')
p.diamond(1, 5, size = 30, alpha = 0.5, legend = 'diamond')
p.diamond_cross(1, 6, size = 30, alpha = 0.5, legend = 'diamond_cross')
p.inverted_triangle(2, 1, size = 30, alpha = 0.5, legend = 'inverted_triangle')
p.square(2, 2, size = 30, alpha = 0.5, legend = 'square')
p.square_cross(2, 3, size = 30, alpha = 0.5, legend = 'square_cross')
p.square_x(2, 4, size = 30, alpha = 0.5, legend = 'square_x')
p.triangle(2, 5, size = 30, alpha = 0.5, legend = 'triangle')
p.x(2, 6, size = 30, alpha = 0.5, legend = 'x')

p.legend.location = "bottom_right"
# 設置圖例位置

show(p)
# 詳細參數可參考文檔:http://bokeh.pydata.org/en/latest/docs/reference/plotting.html#bokeh.plotting.figure.Figure.circle

    選擇合適的散點

  

 

 

 

 

四  直線圖和面積圖

  這里引入了bokeh的數據類型 ColumnColumnDataSource 

  折線圖 p.line / p.multi_line

  面積圖 p.patch  / p.paches  這個輪子可用,不用自己再造

 

from bokeh.models import ColumnDataSource
# 導入ColumnDataSource模塊
# 將數據存儲為ColumnDataSource對象
# 參考文檔:http://bokeh.pydata.org/en/latest/docs/user_guide/data.html
# 可以將dict、Dataframe、group對象轉化為ColumnDataSource對象

df = pd.DataFrame({'value':np.random.randn(100).cumsum()})
# 創建數據

df.index.name = 'index'
source = ColumnDataSource(data = df)
# 轉化為ColumnDataSource對象
# 這里注意了,index和columns都必須有名稱字段

p = figure(plot_width=600, plot_height=400)
p.line(x='index',y='value',source = source,     # 設置x,y值, source → 數據源
       line_width=1, line_alpha = 0.8, line_color = 'black',line_dash = [10,4])   # 線型基本設置
# 繪制折線圖
p.circle(x='index',y='value',source = source, 
         size = 2,color = 'red',alpha = 0.8)
# 繪制折點

show(p)




# 1、折線圖 - 多線圖
# ① multi_line

df = pd.DataFrame({'A':np.random.randn(100).cumsum(),"B":np.random.randn(100).cumsum()})
# 創建數據

p = figure(plot_width=600, plot_height=400)
p.multi_line([df.index, df.index], [df['A'], df['B']],   # 注意x,y值的設置 → [x1,x2,x3,..], [y1,y2,y3,...]
             color=["firebrick", "navy"],    # 可同時設置 → color= "firebrick"
             alpha=[0.8, 0.6],     # 可同時設置 → alpha = 0.6
             line_width=[2,1],     # 可同時設置 → line_width = 2
            )
# 繪制多段線
# 這里由於需要輸入具體值,故直接用dataframe,或者dict即可

show(p)




# 1、折線圖 - 多線圖
# ② 多個line

x = np.linspace(0.1, 5, 100)
# 創建x值

p = figure(title="log axis example", y_axis_type="log",y_range=(0.001, 10**22))
# 這里設置對數坐標軸

p.line(x, np.sqrt(x), legend="y=sqrt(x)",
       line_color="tomato", line_dash="dotdash")
# line1

p.line(x, x, legend="y=x")
p.circle(x, x, legend="y=x")
# line2,折線圖+散點圖

p.line(x, x**2, legend="y=x**2")
p.circle(x, x**2, legend="y=x**2",fill_color=None, line_color="olivedrab")
# line3

p.line(x, 10**x, legend="y=10^x",line_color="gold", line_width=2)
# line4

p.line(x, x**x, legend="y=x^x",line_dash="dotted", line_color="indigo", line_width=2)
# line5

p.line(x, 10**(x**2), legend="y=10^(x^2)",line_color="coral", line_dash="dashed", line_width=2)
# line6

p.legend.location = "top_left"
p.xaxis.axis_label = 'Domain'
p.yaxis.axis_label = 'Values (log scale)'
# 設置圖例及label

show(p)





# 2、面積圖 - 單維度面積圖

s = pd.Series(np.random.randn(100).cumsum())
s.iloc[0] = 0
s.iloc[-1] = 0
# 創建數據
# 注意設定起始值和終點值為最低點

p = figure(plot_width=600, plot_height=400)
p.patch(s.index, s.values,     # 設置x,y值
        line_width=1, line_alpha = 0.8, line_color = 'black',line_dash = [10,4],   # 線型基本設置
        fill_color = 'black',fill_alpha = 0.2
        )
# 繪制面積圖
# .patch將會把所有點連接成一個閉合面

p.circle(s.index, s.values,size = 5,color = 'red',alpha = 0.8)
# 繪制折點

show(p)






# 2、面積圖 - 面積堆疊圖

from bokeh.palettes import brewer
# 導入brewer模塊

N = 20
cats = 10
rng = np.random.RandomState(1)
df = pd.DataFrame(rng.randint(10, 100, size=(N, cats))).add_prefix('y')
# 創建數據,shape為(2010)

df_top = df.cumsum(axis=1)   # 每一個堆疊面積圖的最高點
df_bottom = df_top.shift(axis=1).fillna({'y0': 0})[::-1]    # 每一個堆疊面積圖的最低點,並反向
df_stack = pd.concat([df_bottom, df_top], ignore_index=True)   # 數據合並,每一組數據都是一個可以圍合成一個面的散點集合
# 得到堆疊面積數據

colors = brewer['Spectral'][df_stack.shape[1]]    # 根據變量數拆分顏色
x = np.hstack((df.index[::-1], df.index))         # 得到圍合順序的index,這里由於一列是20個元素,所以連接成面需要40個點

p = figure(x_range=(0, N-1), y_range=(0, 700))
p.patches([x] * df_stack.shape[1],                       # 得到10組index
          [df_stack[c].values for c in df_stack],     # c為df_stack的列名,這里得到10組對應的valyes
          color=colors, alpha=0.8, line_color=None)   # 設置其他參數

show(p)
View Code

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM