bokeh绘制柱状图——堆叠图——直方图

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 import ColumnDataSource
# 导入图表绘制、图标展示模块
# 导入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   # 整体颜色设置,也可单独设置 → color="firebrick"
       line_width = 1,line_alpha = 0.8,line_color = 'black', line_dash = [5,2],    # 单独设置线参数
       fill_color = 'red',fill_alpha = 0.6    # 单独设置填充颜色参数
      )
# 绘制竖向柱状图

show(p)
image.png

2.单系列柱状图 - 分类设置标签-ColumnDataSource

from bokeh.palettes import Spectral6
from bokeh.transform import factor_cmap
# 导入相关模块

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"]
# 创建一个包含标签的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,    # 加载数据另一个方式
       width=0.9, alpha = 0.8,
       color = factor_cmap('fruits', palette=Spectral6, factors=fruits),    # 设置颜色
       legend="fruits")
# 绘制柱状图,横轴直接显示标签
# factor_cmap(field_name, palette, factors, start=0, end=None, nan_color='gray'):颜色转换模块,生成一个颜色转换对象
# field_name:分类名称
# palette:调色盘
# factors:用于在调色盘中分颜色的参数
# 参考文档: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"
# 其他参数设置

show(p)
image.png

2、多系列柱状图-vbar

from bokeh.transform import dodge
from bokeh.core.properties import value
# 导入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'])
# 创建数据

fruits = df.index.tolist()   # 横坐标
years = df.columns.tolist()    # 系列名

data = {'index':fruits}
for year in years:
    data[year] = df[year].tolist()
print(data)
# 生成数据,数据格式为dict

source = ColumnDataSource(data=data)
# 将数据转化为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) → 转换成一个可分组的对象,value为元素的位置(配合width设置)
# value(val, transform=None) → 按照年份分为dict

p.xgrid.grid_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"
# 其他参数设置
show(p)
#结果:
{'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
# 导入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)
# 创建数据

p = figure(x_range=fruits, plot_height=350, title="Fruit Counts by Year",tools="")
renderers = p.vbar_stack(years,          # 设置堆叠值,这里source中包含了不同年份的值,years变量用于识别不同堆叠层
                         x='fruits',     # 设置x坐标
                         source=source,
                         width=0.9, color=colors,
                         legend=[value(x) for x in years], name=years)
# 绘制堆叠图
# 注意第一个参数需要放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"
# 设置其他参数

show(p)
image.png

4.堆叠图

from bokeh.palettes import GnBu3, OrRd3
# 导入颜色模块

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])      # 绘制出口数据堆叠图

p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
             legend=["%s imports" % x for x in years])      # 绘制进口数据堆叠图,这里值为负值

p.y_range.range_padding = 0.2     # 调整边界间隔
p.ygrid.grid_line_color = None   
p.legend.location = "top_left"
p.axis.minor_tick_line_color = None
p.outline_line_color = None
# 设置其他参数

show(p)
image.png

5.直方图-np.histogram + figure.quad(),不需要构建ColumnDataSource对象

df = pd.DataFrame({'value': np.random.randn(1000)*100})
df.index.name = 'index'
print(df.head())
# 创建数据

hist, edges = np.histogram(df['value'],bins=20)
print(hist[:5])
print(edges)
# 将数据解析成直方图统计格式
# 高阶函数np.histogram(a, bins=10, range=None, weights=None, density=None) 
# a:数据
# bins:箱数
# range:最大最小值的范围,如果不设定则为(a.min(), a.max())
# weights:权重
# density:为True则返回“频率”,为False则返回“计数”
# 返回值1 - hist:每个箱子的统计值(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)
#结果:
            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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,427评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,551评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,747评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,939评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,955评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,737评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,448评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,352评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,834评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,992评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,133评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,815评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,477评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,022评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,147评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,398评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,077评论 2 355

推荐阅读更多精彩内容