Bokeh 绘图基础与常用功能

news/2024/7/3 2:18:27

Reference | Getting started with Bokeh – Medium Post

在 Github 上查看交互式的绘图结果 | Bokeh 绘图入门 – Posted by Paradise

在这篇文章中,从最基本的绘图开始,逐步学习 Bokeh 中常用的绘图功能,目标是能满足大部分基础的绘图需求。

一、绘图基础

创建一个空白画布,并在浏览器中显示结果或者保存到本地:

import bokeh
import bokeh.io
import bokeh.plotting

fig = bokeh.plotting.figure()

bokeh.io.output_file('output.html')
bokeh.io.show(fig)

在画布上添加标记元素:

import numpy as np

fig = bokeh.plotting.figure()
x = np.linspace(-np.pi, np.pi, 30)
fig.line(x, np.sin(x))
bokeh.io.show(fig)

添加多个标记元素,按顺序显示:

fig = bokeh.plotting.figure()
fig.line(x, np.sin(x))
fig.circle(x, np.cos(x), fill_color='orange', size=10)
bokeh.io.show(fig)

二、更多画布设置

设置画布大小和工具栏:

fig = bokeh.plotting.figure(
    plot_width=800, plot_height=400,
    tools='pan, wheel_zoom, lasso_select, tap, undo, reset',
    toolbar_location='below')
bokeh.io.show(fig)

使用 models 转化 DataFrame,用 DataFrame 中的数据绘图,并设置悬停工具提示:

import tushare
import bokeh.models
import pandas as pd

# 获取中国银行股价历史数据,并准备工具提示
df = tushare.get_hist_data('601988')
df['index'] = pd.to_datetime(df.index)
df['Date'] = list(df.index)
df['volume_str'] = round(df.volume/1000).map(lambda x: str(int(x))+' K')
# df['color'] = ['green' if pc<0 else 'red' for pc in df.price_change]

# 转化 DataFrame 得到绘图数据源
source = bokeh.models.ColumnDataSource(df)

# 设置工具提示
hover = bokeh.models.HoverTool(tooltips=[
            ("Date", "@Date"),
            ("Open", "@open"),
            ("High", "@high"),
            ("Low", "@low"),
            ("Close", "@close"),
            ("Volume", "@volume_str")])

# 绘图(时序数据)
fig = bokeh.plotting.figure(
    x_axis_type='datetime', 
    plot_width=800, plot_height=400,
    tools=[hover], toolbar_location=None,       # 工具提示
    title='BOC Stock Prices',                   # 标题
    x_axis_label='Date', y_axis_label='Price'   # 轴标签
    )
fig.line(x='index', y='close', source=source)
# fig.vbar(x='index', top='price_change', width=1, color='color', source=source)
bokeh.io.show(fig)

More examples for HoverTool

三、颜色设置

Documents of palettes

使用调色板映射数据标记,线性颜色映射:

import bokeh.palettes
import bokeh.transform

x = np.linspace(0, 10, 100)
mapper = bokeh.transform.linear_cmap(
    field_name='y',     # 对纵坐标数值进行映射
    palette=bokeh.palettes.Spectral6,   # 所有调色板:dir(bokeh.palettes)
    low=-1, high=1      # 映射数值范围
    )

fig = bokeh.plotting.figure(plot_width=600, plot_height=300)
fig.circle(x, np.sin(x), color=mapper, size=8)
bokeh.io.show(fig)

对数映射:

mapper = bokeh.transform.log_cmap(
    field_name='y',
    palette=bokeh.palettes.Plasma8,
    low=0, high=1024)
fig = bokeh.plotting.figure(plot_width=600, plot_height=300)
fig.circle(x, 2**x, color=mapper, size=8)
bokeh.io.show(fig)

四、子图排列与关联

通过 layouts 子模块设置多个子图, 单行或单列布局:

import bokeh.layouts

def make_plot(func):
    fig = bokeh.plotting.figure(plot_width=400, plot_height=400, toolbar_location=None)
    x = np.linspace(-np.pi, np.pi, 100)
    fig.line(x, func(x))
    return fig
figs = [make_plot(func) for func in [np.sin, np.cos, np.tan]]

subplots = bokeh.layouts.row(*figs)     # 纵向布局使用 bokeh.layouts.column
bokeh.io.show(subplots)

网格布局:

figs = [make_plot(func) for func in [np.sin, np.cos, np.tan]]
subplots = bokeh.layouts.gridplot([[figs[0],figs[1]], [None,figs[2]]])
bokeh.io.show(subplots)

使用标签页进行布局,并联结每个子图的轴范围:

import bokeh.models.widgets as widgets

figs = [make_plot(func) for func in [np.sin, np.cos, np.tan]]
# 令图 1 和图 2 的轴范围在交互时同步变动
figs[0].x_range = figs[1].x_range
figs[0].y_range = figs[1].y_range

tab1 = widgets.Panel(child=bokeh.layouts.row(figs[0], figs[1]), title='Sheet1')
tab2 = widgets.Panel(child=bokeh.layouts.row(figs[2]), title='Sheet2')
tabs = widgets.Tabs(tabs=[tab1, tab2])
bokeh.io.show(tabs)


http://lihuaxi.xjx100.cn/news/1292445.html

相关文章

关于在容器中,nignx代理后端多个服务如何保证后端服务的地址不变呢?

关于在容器中&#xff0c;nignx代理后端多个服务如何保证后端服务的地址不变呢&#xff1f; 有什么方法 第一种 如果你的后端服务的IP地址不会随着每一次的版本迭代而发生变化&#xff0c;那么就相当于host network 第二种 如果你的后端服务的IP地址每次都会发生变化 &#xf…

新品预告——旗舰级DG4Pros最详技术解析及应用方案介绍

旗舰级DG4Pros RIY-DG4Pros是目前睿铂性能指标最高的一款全画幅倾斜摄影相机&#xff0c;其核心光学组件部分由睿铂结合多年来的用户反馈与对倾斜摄影技术的探索成果&#xff0c;完全自主研发设计&#xff0c;技术水平领先于市面同类产品。相机镜头内置双高斯结构和超低色散非…

【JavaWeb】Cookie和Session的使用场景

一、Cookie 简介 Cookie —— 浏览器提供的一种持久化存储的机制。 为什么有浏览器需要给用户提供Cookie 这种持久化存储呢&#xff0c;直接存硬盘不好吗&#xff0c;换而言之 Cookie机制到底是个啥&#xff1f;&#xff1f;&#xff1f; 早期浏览器为了避免用户访问恶意网…

解决vmware虚拟机,克隆修改ip后,xshell连接不上问题

1、查看网卡 ifconfig2、修改网卡配置 vim /etc/sysconfig/network-scripts/ifcfg-ens32 改成与上图一样 修改后 3、重启reboot则解决

const、var、let用法

var 当使用 var 声明变量时&#xff0c;该变量的作用域是在最近的函数体内&#xff0c;而不是块级作用域&#xff08;例如 if 语句、for 循环等&#xff09;。这意味着在函数内部&#xff0c;无论变量是在函数的哪个位置声明的&#xff0c;它都可以被访问到。 另外&#xff0…

哪个爬虫库用的最多?

在Python中&#xff0c;最常用的爬虫库是requests和BeautifulSoup。requests库用于发送HTTP请求和处理响应&#xff0c;而BeautifulSoup库用于解析HTML文档。这两个库通常结合使用&#xff0c;用于爬取网页内容并提取所需的数据。其他常用的爬虫库还包括Scrapy、Selenium等。 常…

JMeter 后置处理器之JSON提取器

目录 前言&#xff1a; 测试环境 插件介绍 插件参数 插件使用示例 JSON-PATH表达式介绍 操作符 函数 过滤器操作符 JSON PATH示例 前言&#xff1a; JMeter是一个功能强大的性能测试工具&#xff0c;它提供了许多后置处理器来处理和提取测试结果。其中一个常用的后…

详细介绍如何使用 OpenCV 实现自动文档扫描仪--附实现源码

文末附相关源代码实现的免费下载链接 文档扫描是将物理文档转换为数字形式的过程。可以通过扫描仪或手机摄像头拍摄图像来完成。我们将在本教程中讨论如何使用计算机视觉和图像处理技术有效地实现这一目标。 在当今的计算机时代,几乎不需要任何物理文书工作。尽管如此,在仍…