导入数据包

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. %matplotlib inline
  5. import warnings
  6. warnings.filterwarnings('ignore')
  7. #不发出警告
  8. from bokeh.io import output_notebook
  9. output_notebook()
  10. #导入绘图模块
  11. from bokeh.plotting import figure, show
  12. from bokeh.models import ColumnDataSource
  13. #导入绘图模块、展示模块
  14. #导入ColumsDataSource模块

单系列柱状图—vbar

  1. # 1、单系列柱状图
  2. # vbar 竖向柱状图
  3. p = figure(plot_width = 600, plot_height = 400)
  4. p.vbar(x = [1, 2, 3], #设置柱状图的位置,这里数据可以是一个Serice的index
  5. width = 0.4, #设置柱状图的宽度
  6. bottom = [0, 0, 0], #设置柱状图底部的位置
  7. top = [1.2, 2.5, 3.7], #设置柱状图顶部的位置,这里数据可以是一个Serice的values
  8. line_width = 2, #设置柱状图边框的粗细
  9. line_color = 'black', #设置柱状图边框的颜色
  10. line_alpha = 0.6, #设置柱状图边框线的透明度
  11. line_dash = [10, 5], #设置柱状图边框为虚线显示
  12. fill_color = 'red', #设置柱状图内部填充颜色
  13. fill_alpha = 0.7, #设置柱状图内部颜色的透明度
  14. )
  15. show(p)

图片.png


单系列柱状图—hbar

  1. # 1、单系列柱状图
  2. # hbar
  3. df = pd.DataFrame({'value' : np.random.randn(100)*10,
  4. 'color' : np.random.choice(['red', 'yellow', 'blue'], 100)})
  5. p = figure(plot_width = 600, plot_height = 400)
  6. p.hbar(y = df.index, #设置柱状图的位置
  7. height = 0.5, #设置柱状图的宽度
  8. left = 0, #设置柱状图左边最小值
  9. right = df['value'], #设置柱状图右边的最大值
  10. color = df.color #社渚柱状图的颜色
  11. )
  12. show(p)

图片.png


单系列柱状图—分类设置标签(ColumnDataSource)

  1. from bokeh.palettes import Spectral6
  2. from bokeh.transform import factor_cmap
  3. #导入相关模块
  4. fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
  5. counts = [5, 6, 4, 2, 4, 6 ]
  6. source = ColumnDataSource(data = dict(fruits = fruits, counts = counts))
  7. colors = ['salmon', 'olive', 'darkred', 'goldenrod', 'skyblue', 'orange']
  8. #创建一个包含标签的data,对象类型为ColumnDatasource
  9. p = figure(x_range = fruits, y_range = (0, 9), plot_height = 350, title = 'Fruit Counts', tools = '')
  10. p.vbar(x = 'fruits', top = 'counts', source = source, #加载数据
  11. width = 0.8, alpha = 0.8,
  12. color = factor_cmap('fruits', palette=Spectral6, factors=fruits), #设置颜色
  13. legend = 'fruits'
  14. )
  15. # 绘制柱状图,横轴直接显示标签
  16. # factor_cmap(field_name, palette, factors, start=0, end=None, nan_color='gray'):颜色转换模块,生成一个颜色转换对象
  17. # field_name:分类名称
  18. # palette:调色盘
  19. # factors:用于在调色盘中分颜色的参数
  20. # 参考文档:http://bokeh.pydata.org/en/latest/docs/reference/transform.html
  21. p.xgrid.grid_line_color = None
  22. p.legend.orientation = 'horizontal'
  23. p.legend.location = 'top_center'
  24. # 其他参数设置
  25. show(p)

图片.png


多系列柱状图

  1. # 多系列柱状图
  2. # vbar
  3. from bokeh.transform import dodge
  4. from bokeh.core.properties import value
  5. #导入dodge、value模块
  6. df = pd.DataFrame({'2015':[2, 1, 4, 3, 2, 4], '2016':[5, 3, 3, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]},
  7. index = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'])
  8. #创建数据
  9. fruits = df.index.tolist() #横坐标名
  10. years = df.columns.tolist() #纵坐标名
  11. data = {'index' : fruits}
  12. for year in years:
  13. data[year] = df[year].tolist()
  14. #生成数据,数据格式为dict
  15. source = ColumnDataSource(data = data)
  16. #将数据转化为ColumnDataSource对象
  17. p = figure(x_range = fruits, y_range = (0, 10), plot_height = 350, title = 'Fruit Counts by Year')
  18. p.vbar(x = dodge('index', -0.25, range = p.x_range), top = '2015', width = 0.2, source = source, color = 'red', legend = value('2015'))
  19. p.vbar(x = dodge('index', 0, range = p.x_range), top = '2016', width = 0.2, source = source, color = 'yellow', legend = value('2016'))
  20. p.vbar(x = dodge('index', 0.25, range = p.x_range), top = '2017', width = 0.2, source = source, color = 'blue', legend = value('2017'))
  21. show(p)

图片.png
Bokeh所能识别的数据结构,是Python自身的数据结构,例如list和dict等数据结构,不过新版本得也开始兼容DataFarme和Serice数据类型


堆叠图—竖图

  1. from bokeh.core.properties import value
  2. #导入value模块
  3. fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
  4. years = ['2015', '2016', '2017']
  5. colors = ["#c9d9d3", "#718dbf", "#e84d60"]
  6. data = {'fruits' : fruits,
  7. '2015' : [2, 1, 4, 3, 2, 4],
  8. '2016' : [5, 3, 4, 2, 4, 6],
  9. '2017' : [3, 2, 4, 4, 5, 3]}
  10. source = ColumnDataSource(data)
  11. #创建数据
  12. p = figure(x_range = fruits, plot_height = 350, title = 'Fruit Counts by Year', tools = '')
  13. renderers = p.vbar_stack(years, #设置堆叠值,这里source包含了不同年份的值,years变量用于识别不同的对叠层
  14. x = 'fruits', #设置x轴坐标
  15. source = source,
  16. width = 0.9,
  17. color = colors,
  18. legend = [value(x) for x in years],
  19. name = years
  20. )
  21. # 绘制堆叠图
  22. # 注意第一个参数需要放years
  23. p.xgrid.grid_line_color = None
  24. p.axis.minor_tick_line_color = None
  25. p.outline_line_color = None
  26. p.legend.location = 'top_left'
  27. p.legend.orientation = 'horizontal'
  28. 设置其他参数
  29. show(p)

图片.png


堆叠图—横图

  1. 堆叠图
  2. from bokeh.palettes import GnBu3, OrRd3
  3. # 导入颜色模块
  4. fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
  5. years = ["2015", "2016", "2017"]
  6. exports = {'fruits' : fruits,
  7. '2015' : [2, 1, 4, 3, 2, 4],
  8. '2016' : [5, 3, 4, 2, 4, 6],
  9. '2017' : [3, 2, 4, 4, 5, 3]}
  10. imports = {'fruits' : fruits,
  11. '2015' : [-1, 0, -1, -3, -2, -1],
  12. '2016' : [-2, -1, -3, -1, -2, -2],
  13. '2017' : [-1, -2, -1, 0, -2, -2]}
  14. p = figure(y_range=fruits, plot_height=350, x_range=(-16, 16), title="Fruit import/export, by year")
  15. p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
  16. legend=["%s exports" % x for x in years]) # 绘制出口数据堆叠图
  17. p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
  18. legend=["%s imports" % x for x in years]) # 绘制进口数据堆叠图,这里值为负值
  19. p.y_range.range_padding = 0.2 # 调整边界间隔
  20. p.ygrid.grid_line_color = None
  21. p.legend.location = "top_left"
  22. p.axis.minor_tick_line_color = None
  23. p.outline_line_color = None
  24. # 设置其他参数
  25. show(p)

图片.png


直方图

  1. # 4、直方图
  2. # np.histogram + figure.quad()
  3. # 不需要构建ColumnDataSource对象
  4. df = pd.DataFrame({'value': np.random.randn(1000)*100})
  5. df.index.name = 'index'
  6. print(df.head())
  7. # 创建数据
  8. hist, edges = np.histogram(df['value'],bins=20)
  9. print(hist[:5])
  10. print(edges)
  11. #hist代表不同箱子中,数的个数
  12. #edges代表将数据分成不同的箱子以后,每一个箱子的位置坐标
  13. # 将数据解析成直方图统计格式
  14. # 高阶函数np.histogram(a, bins=10, range=None, weights=None, density=None)
  15. # a:数据
  16. # bins:箱数
  17. # range:最大最小值的范围,如果不设定则为(a.min(), a.max())
  18. # weights:权重
  19. # density:为True则返回“频率”,为False则返回“计数”
  20. # 返回值1 - hist:每个箱子的统计值(top)
  21. # 返回值2 - edges:每个箱子的位置坐标,这里n个bins将会有n+1个edges
  22. p = figure(title="HIST", tools="save",background_fill_color="#E8DDCB")
  23. p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], # 分别代表每个柱子的四边值
  24. fill_color="#036564", line_color="#033649")
  25. # figure.quad绘制直方图
  26. show(p)

图片.png