bokeh繪制柱狀圖——堆疊圖——直方圖

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

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

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

from bokeh.plotting import figure,show
from bokeh.models import ColumnDataSource
# 導(dǎo)入圖表繪制、圖標展示模塊
# 導(dǎo)入ColumnDataSource模塊

1、單系列柱狀圖-vbar

p = figure(plot_width=400, plot_height=400)
p.vbar(x=[1, 2, 3], width=0.5, bottom=0,top=[1.2, 2.5, 3.7],  # x:橫軸坐標,width:寬度,bottom:底高度,top:頂高度
       #color = ['red','blue','green'], alpha = 0.8   # 整體顏色設(shè)置,也可單獨設(shè)置 → color="firebrick"
       line_width = 1,line_alpha = 0.8,line_color = 'black', line_dash = [5,2],    # 單獨設(shè)置線參數(shù)
       fill_color = 'red',fill_alpha = 0.6    # 單獨設(shè)置填充顏色參數(shù)
      )
# 繪制豎向柱狀圖

show(p)
image.png

2.單系列柱狀圖 - 分類設(shè)置標簽-ColumnDataSource

from bokeh.palettes import Spectral6
from bokeh.transform import factor_cmap
# 導(dǎo)入相關(guān)模塊

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 6]
source = ColumnDataSource(data=dict(fruits=fruits, counts=counts))
colors = [ "salmon", "olive", "darkred", "goldenrod", "skyblue", "orange"]
# 創(chuàng)建一個包含標簽的data,對象類型為ColumnDataSource

p = figure(x_range=fruits, y_range=(0,9), plot_height=350, title="Fruit Counts",tools="")
#plot_height=350高度
p.vbar(x='fruits', top='counts', source=source,    # 加載數(shù)據(jù)另一個方式
       width=0.9, alpha = 0.8,
       color = factor_cmap('fruits', palette=Spectral6, factors=fruits),    # 設(shè)置顏色
       legend="fruits")
# 繪制柱狀圖,橫軸直接顯示標簽
# factor_cmap(field_name, palette, factors, start=0, end=None, nan_color='gray'):顏色轉(zhuǎn)換模塊,生成一個顏色轉(zhuǎn)換對象
# field_name:分類名稱
# palette:調(diào)色盤
# factors:用于在調(diào)色盤中分顏色的參數(shù)
# 參考文檔:http://bokeh.pydata.org/en/latest/docs/reference/transform.html

p.xgrid.grid_line_color = None
p.legend.orientation = "horizontal"
p.legend.location = "top_center"
# 其他參數(shù)設(shè)置

show(p)
image.png

2、多系列柱狀圖-vbar

from bokeh.transform import dodge
from bokeh.core.properties import value
# 導(dǎo)入dodge、value模塊

df = pd.DataFrame({'2015':[2, 1, 4, 3, 2, 4],'2016':[5, 3, 3, 2, 4, 6], '2017':[3, 2, 4, 4, 5, 3]},
                 index = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'])
# 創(chuàng)建數(shù)據(jù)

fruits = df.index.tolist()   # 橫坐標
years = df.columns.tolist()    # 系列名

data = {'index':fruits}
for year in years:
    data[year] = df[year].tolist()
print(data)
# 生成數(shù)據(jù),數(shù)據(jù)格式為dict

source = ColumnDataSource(data=data)
# 將數(shù)據(jù)轉(zhuǎn)化為ColumnDataSource對象

p = figure(x_range=fruits, y_range=(0, 10), plot_height=350, title="Fruit Counts by Year",tools="")

p.vbar(x=dodge('index', -0.25, range=p.x_range), top='2015', width=0.2, source=source,color="#c9d9d3", legend=value("2015"))
p.vbar(x=dodge('index',  0.0,  range=p.x_range), top='2016', width=0.2, source=source,color="#718dbf", legend=value("2016"))
p.vbar(x=dodge('index',  0.25, range=p.x_range), top='2017', width=0.2, source=source,color="#e84d60", legend=value("2017"))
# 繪制多系列柱狀圖
# dodge(field_name, value, range=None) → 轉(zhuǎn)換成一個可分組的對象,value為元素的位置(配合width設(shè)置)
# value(val, transform=None) → 按照年份分為dict

p.xgrid.grid_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"
# 其他參數(shù)設(shè)置
show(p)
#結(jié)果:
{'index': ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'], '2015': [2, 1, 4, 3, 2, 4], '2016': [5, 3, 3, 2, 4, 6], '2017': [3, 2, 4, 4, 5, 3]}
image.png

3、堆疊圖

from bokeh.core.properties import value
# 導(dǎo)入value模塊

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
colors = ["#c9d9d3", "#718dbf", "#e84d60"]
data = {'fruits' : fruits,
        '2015'   : [2, 1, 4, 3, 2, 4],
        '2016'   : [5, 3, 4, 2, 4, 6],
        '2017'   : [3, 2, 4, 4, 5, 3]}
source = ColumnDataSource(data=data)
# 創(chuàng)建數(shù)據(jù)

p = figure(x_range=fruits, plot_height=350, title="Fruit Counts by Year",tools="")
renderers = p.vbar_stack(years,          # 設(shè)置堆疊值,這里source中包含了不同年份的值,years變量用于識別不同堆疊層
                         x='fruits',     # 設(shè)置x坐標
                         source=source,
                         width=0.9, color=colors,
                         legend=[value(x) for x in years], name=years)
# 繪制堆疊圖
# 注意第一個參數(shù)需要放years

p.xgrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"
# 設(shè)置其他參數(shù)

show(p)
image.png

4.堆疊圖

from bokeh.palettes import GnBu3, OrRd3
# 導(dǎo)入顏色模塊

fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
exports = {'fruits' : fruits,
           '2015'   : [2, 1, 4, 3, 2, 4],
           '2016'   : [5, 3, 4, 2, 4, 6],
           '2017'   : [3, 2, 4, 4, 5, 3]}
imports = {'fruits' : fruits,
           '2015'   : [-1, 0, -1, -3, -2, -1],
           '2016'   : [-2, -1, -3, -1, -2, -2],
           '2017'   : [-1, -2, -1, 0, -2, -2]}

p = figure(y_range=fruits, plot_height=350, x_range=(-16, 16), title="Fruit import/export, by year")

p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
             legend=["%s exports" % x for x in years])      # 繪制出口數(shù)據(jù)堆疊圖

p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
             legend=["%s imports" % x for x in years])      # 繪制進口數(shù)據(jù)堆疊圖,這里值為負值

p.y_range.range_padding = 0.2     # 調(diào)整邊界間隔
p.ygrid.grid_line_color = None   
p.legend.location = "top_left"
p.axis.minor_tick_line_color = None
p.outline_line_color = None
# 設(shè)置其他參數(shù)

show(p)
image.png

5.直方圖-np.histogram + figure.quad(),不需要構(gòu)建ColumnDataSource對象

df = pd.DataFrame({'value': np.random.randn(1000)*100})
df.index.name = 'index'
print(df.head())
# 創(chuàng)建數(shù)據(jù)

hist, edges = np.histogram(df['value'],bins=20)
print(hist[:5])
print(edges)
# 將數(shù)據(jù)解析成直方圖統(tǒng)計格式
# 高階函數(shù)np.histogram(a, bins=10, range=None, weights=None, density=None) 
# a:數(shù)據(jù)
# bins:箱數(shù)
# range:最大最小值的范圍,如果不設(shè)定則為(a.min(), a.max())
# weights:權(quán)重
# density:為True則返回“頻率”,為False則返回“計數(shù)”
# 返回值1 - hist:每個箱子的統(tǒng)計值(top)
# 返回值2 - edges:每個箱子的位置坐標,這里n個bins將會有n+1個edges

p = figure(title="HIST", tools="save",background_fill_color="#E8DDCB")
p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],   # 分別代表每個柱子的四邊值
        fill_color="#036564", line_color="#033649")
# figure.quad繪制直方圖

show(p)
#結(jié)果:
            value
index            
0       -6.749140
1       29.988627
2       -8.200213
3     -107.498925
4      -10.983780
[1 0 0 2 5]
[-4.15892896e+02 -3.81201622e+02 -3.46510349e+02 -3.11819075e+02
 -2.77127802e+02 -2.42436528e+02 -2.07745254e+02 -1.73053981e+02
 -1.38362707e+02 -1.03671433e+02 -6.89801597e+01 -3.42888861e+01
  4.02387569e-01  3.50936612e+01  6.97849349e+01  1.04476208e+02
  1.39167482e+02  1.73858756e+02  2.08550029e+02  2.43241303e+02
  2.77932577e+02]
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容