hvplot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

hvPlot Development Skills

hvPlot 开发技巧

This document provides best practices for developing plots and charts with HoloViz hvPlot in notebooks and .py files.
Please develop as an Expert Python Developer developing advanced data-driven, analytics and testable data visualisations, dashboards and applications would do. Keep the code short, concise, documented, testable and professional.
本文档提供了在笔记本和.py文件中使用HoloViz hvPlot开发图表的最佳实践。
请以资深Python开发者的视角进行开发,打造高级数据驱动、可分析且可测试的数据可视化图表、仪表盘及应用。保持代码简洁、带有文档注释、可测试且专业。

Dependencies

依赖项

Core dependencies provided with the
hvplot
Python package:
  • hvplot: Core visualization framework
  • holoviews: Declarative data visualization library with composable elements. Best for: complex multi-layered plots, advanced interactivity (linked brushing, selection), when you need fine control over plot composition, scientific visualizations. More powerful but steeper learning curve than hvPlot. hvPlot is built upon holoviews.
  • colorcet: Perceptually uniform colormaps
  • panel: Provides widgets and layouts enabling tool, dashboard and data app development.
  • param: A declarative approach to creating classes with typed, validated, and documented parameters. Fundamental to the reactive programming model of hvPlot and the rest of the HoloViz ecosystem.
  • pandas: Industry-standard DataFrame library for tabular data. Best for: data cleaning, transformation, time series analysis, datasets that fit in memory. The default choice for most data work.
Optional dependencies from the HoloViz Ecosystem:
  • datashader: Renders large datasets (millions+ points) into images for visualization. Best for: big data visualization, geospatial datasets, scatter plots with millions of points, heatmaps of dense data. Requires hvPlot or HoloViews as frontend.
  • geoviews: Geographic data visualization with map projections and tile sources. Best for: geographic/geospatial plots, map-based dashboards, when you need coordinate systems and projections. Built on HoloViews, works seamlessly with hvPlot.
  • holoviz-mcp: Model Context Protocol server for HoloViz ecosystem. Provides access to detailed documentation, component search and agent skills.
  • hvsampledata: Shared datasets for the HoloViz projects.
hvplot
Python包提供的核心依赖:
  • hvplot:核心可视化框架
  • holoviews:声明式数据可视化库,支持可组合元素。最适用于:复杂多层图表、高级交互(联动刷选、选择功能)、需要精细控制图表组合的场景、科学可视化。功能比hvPlot更强大,但学习曲线更陡。hvPlot基于holoviews构建。
  • colorcet:感知均匀的颜色映射集
  • panel:提供组件与布局,支持工具、仪表盘和数据应用开发。
  • param:用于创建带类型验证、文档化参数的类的声明式方法。是hvPlot及整个HoloViz生态响应式编程模型的基础。
  • pandas:行业标准的表格数据DataFrame库。最适用于:数据清洗、转换、时间序列分析、可放入内存的数据集。是大多数数据处理工作的默认选择。
HoloViz生态的可选依赖:
  • datashader:将大型数据集(百万级以上数据点)渲染为图像以实现可视化。最适用于:大数据可视化、地理空间数据集、百万级数据点的散点图、高密度数据的热力图。需要hvPlot或HoloViews作为前端。
  • geoviews:带地图投影和瓦片源的地理数据可视化库。最适用于:地理/地理空间图表、基于地图的仪表盘、需要坐标系和投影的场景。基于HoloViews构建,可与hvPlot无缝协作。
  • holoviz-mcp:HoloViz生态的模型上下文协议服务器。提供详细文档、组件搜索和技能查询功能。
  • hvsampledata:HoloViz项目的共享数据集。

Installation for Development

开发环境安装

bash
pip install hvplot hvsampledata panel watchfiles
For development in .py files DO always include watchfiles for Panel hotreload.
bash
pip install hvplot hvsampledata panel watchfiles
在.py文件中开发时,请务必安装watchfiles以支持Panel热重载。

Earthquake Sample Data

地震示例数据

In the example below we will use the
earthquakes
sample data:
python
import hvsampledata

hvsampledata.earthquakes("pandas")
text
Tabular record of earthquake events from the USGS Earthquake Catalog that provides detailed
information including parameters such as time, location as latitude/longitude coordinates
and place name, depth, and magnitude. The dataset contains 596 events.

Note: The columns `depth_class` and `mag_class` were created by categorizing numerical values from
the `depth` and `mag` columns in the original dataset using custom-defined binning:

Depth Classification

| depth     | depth_class  |
|-----------|--------------|
| Below 70  | Shallow      |
| 70 - 300  | Intermediate |
| Above 300 | Deep         |

Magnitude Classification

| mag         | mag_class |
|-------------|-----------|
| 3.9 - <4.9  | Light     |
| 4.9 - <5.9  | Moderate  |
| 5.9 - <6.9  | Strong    |
| 6.9 - <7.9  | Major     |


Schema
------
| name        | type       | description                                                         |
|:------------|:-----------|:--------------------------------------------------------------------|
| time        | datetime   | UTC Time when the event occurred.                                   |
| lat         | float      | Decimal degrees latitude. Negative values for southern latitudes.   |
| lon         | float      | Decimal degrees longitude. Negative values for western longitudes   |
| depth       | float      | Depth of the event in kilometers.                                   |
| depth_class | category   | The depth category derived from the depth column.                   |
| mag         | float      | The magnitude for the event.                                        |
| mag_class   | category   | The magnitude category derived from the mag column.                 |
| place       | string     | Textual description of named geographic region near to the event.   |
以下示例中我们将使用
earthquakes
示例数据:
python
import hvsampledata

hvsampledata.earthquakes("pandas")
text
来自美国地质调查局(USGS)地震目录的地震事件表格记录,包含事件发生时间、经纬度位置及地名、深度、震级等详细参数。数据集包含596条事件记录。

注意:`depth_class`和`mag_class`列是通过自定义分箱规则,对原始数据集中的`depth`和`mag`列数值进行分类得到的:

深度分类

| depth     | depth_class  |
|-----------|--------------|
| 小于70    | Shallow      |
| 70-300    | Intermediate |
| 大于300   | Deep         |

震级分类

| mag         | mag_class |
|-------------|-----------|
| 3.9-<4.9    | Light     |
| 4.9-<5.9    | Moderate  |
| 5.9-<6.9    | Strong    |
| 6.9-<7.9    | Major     |


数据结构
------
| name        | type       | description                                                         |
|:------------|:-----------|:--------------------------------------------------------------------|
| time        | datetime   | 事件发生的UTC时间。                                                 |
| lat         | float      | 十进制纬度值。负值表示南纬。                                       |
| lon         | float      | 十进制经度值。负值表示西经。                                       |
| depth       | float      | 事件深度(单位:千米)。                                           |
| depth_class | category   | 由depth列派生的深度分类。                                           |
| mag         | float      | 事件震级。                                                          |
| mag_class   | category   | 由mag列派生的震级分类。                                             |
| place       | string     | 事件附近已命名地理区域的文字描述。                                 |

Reference Data Exploration Example

参考数据探索示例

Below is a simple reference example for data exploration.
python
import hvsampledata
以下是一个简单的数据探索参考示例。
python
import hvsampledata

DO import panel if working in .py files

在.py文件中工作时,请导入panel

import panel as pn
import panel as pn

Do importing hvplot.pandas to add .hvplot namespace to Pandas DataFrames and Series

导入hvplot.pandas,为Pandas DataFrame和Series添加.hvplot命名空间

import hvplot.pandas # noqa: F401
import hvplot.pandas # noqa: F401

DO always run pn.extension() to load panel javascript extensions

请始终运行pn.extension()以加载panel的JavaScript扩展

pn.extension()
pn.extension()

Do keep the extraction, transformation and plotting of data clearly separate

请将数据提取、转换和绘图代码清晰分离

Extract: earthquakes sample data

提取:地震示例数据

data = hvsampledata.earthquakes("pandas")
data = hvsampledata.earthquakes("pandas")

Transform: Group by mag_class and count occurrences

转换:按mag_class分组并统计数量

mag_class_counts = data.groupby('mag_class').size().reset_index(name='counts')
mag_class_counts = data.groupby('mag_class').size().reset_index(name='counts')

Plot: counts by mag_class

绘图:按mag_class统计的数量

plot = mag_class_counts.hvplot.bar(x='mag_class', y='counts', title='Earthquake Counts by Magnitude Class')
plot = mag_class_counts.hvplot.bar(x='mag_class', y='counts', title='按震级分类的地震数量')

If working in notebook DO output to plot:

如果在笔记本中工作,请直接输出图表:

plot
plot

Else if working in .py file DO:

如果在.py文件中工作,请:

DO provide a method to serve the app with
panel serve

请提供通过
panel serve
启动应用的方法

if pn.state.served: # DO remember to add .servable to the panel components you want to serve with the app pn.panel(plot, sizing_mode="stretch_both").servable()
if pn.state.served: # 请记得为要随应用一起部署的panel组件添加.servable() pn.panel(plot, sizing_mode="stretch_both").servable()

DON'T provide a
if __name__ == "__main__":
method to serve the app with
python

不要使用
if __name__ == "__main__":
方法通过
python
命令启动应用


If working in a .py file DO always serve the plot with hotreload for manual testing while developing:

```bash
panel serve path/to/file.py --dev --show
DONT serve with
python path_to_this_file.py
.

如果在.py文件中工作,请始终通过带热重载的方式启动服务以进行开发期间的手动测试:

```bash
panel serve path/to/file.py --dev --show
不要使用
python path_to_this_file.py
启动服务。

General Instructions

通用说明

  • Always import hvplot for your data backend:
python
import hvplot.pandas # will add .hvplot namespace to Pandas dataframes
import hvplot.polars # will add .hvplot namespace to Polars dataframes
...
  • Prefer Bokeh > Plotly > Matplotlib plotting backend for interactivity
  • DO use bar charts over pie Charts. Pie charts are not supported.
  • DO use NumeralTickFormatter and 'a' formatter for axis formatting:
python
from bokeh.models.formatters import NumeralTickFormatter

df.hvplot(
    ...,
    yformatter=NumeralTickFormatter(format='0.00a'),  # Format as 1.00M, 2.50M, etc.
)
InputFormat StringOutput
1230974'0.0a'1.2m
1460'0 a'1 k
-104000'0a'-104k
  • For detailed styling and publication quality charts use HoloViz instead of hvPlot.
  • 始终为你的数据后端导入hvplot:
python
import hvplot.pandas # 为Pandas DataFrame添加.hvplot命名空间
import hvplot.polars # 为Polars DataFrame添加.hvplot命名空间
...
  • 为实现交互性,优先选择Bokeh > Plotly > Matplotlib绘图后端
  • 请使用柱状图而非饼图。hvPlot不支持饼图。
  • 请使用NumeralTickFormatter和'a'格式化器进行轴格式化:
python
from bokeh.models.formatters import NumeralTickFormatter

df.hvplot(
    ...,
    yformatter=NumeralTickFormatter(format='0.00a'),  # 格式化为1.00M、2.50M等
)
输入值格式字符串输出值
1230974'0.0a'1.2m
1460'0 a'1 k
-104000'0a'-104k
  • 如需精细样式和出版级图表,请使用HoloViz而非hvPlot。

Developing

开发实践

When developing a hvplot please serve it for development using Panel:
python
import pandas as pd
import hvplot.pandas  # noqa
import panel as pn

import numpy as np

np.random.seed(42)
dates = pd.date_range("2022-08-01", periods=30, freq="B")
open_prices = np.cumsum(np.random.normal(100, 2, size=len(dates)))
high_prices = open_prices + np.random.uniform(1, 5, size=len(dates))
low_prices = open_prices - np.random.uniform(1, 5, size=len(dates))
close_prices = open_prices + np.random.uniform(-3, 3, size=len(dates))

data = pd.DataFrame({
    "open": open_prices.round(2),
    "high": high_prices.round(2),
    "low": low_prices.round(2),
    "close": close_prices.round(2),
}, index=dates)
开发hvplot图表时,请通过Panel启动服务:
python
import pandas as pd
import hvplot.pandas  # noqa
import panel as pn

import numpy as np

np.random.seed(42)
dates = pd.date_range("2022-08-01", periods=30, freq="B")
open_prices = np.cumsum(np.random.normal(100, 2, size=len(dates)))
high_prices = open_prices + np.random.uniform(1, 5, size=len(dates))
low_prices = open_prices - np.random.uniform(1, 5, size=len(dates))
close_prices = open_prices + np.random.uniform(-3, 3, size=len(dates))

data = pd.DataFrame({
    "open": open_prices.round(2),
    "high": high_prices.round(2),
    "low": low_prices.round(2),
    "close": close_prices.round(2),
}, index=dates)

Create a scatter plot of date vs close price

创建日期与收盘价的散点图

scatter_plot = data.hvplot.scatter(x="index", y="close", grid=True, title="Close Price Scatter Plot", xlabel="Date", ylabel="Close Price")
scatter_plot = data.hvplot.scatter(x="index", y="close", grid=True, title="收盘价散点图", xlabel="日期", ylabel="收盘价")

Create a Panel app

创建Panel应用

app = pn.Column("# Close Price Scatter Plot", scatter_plot)
if pn.state.served: app.servable()

```bash
panel serve plot.py --dev
app = pn.Column("# 收盘价散点图", scatter_plot)
if pn.state.served: app.servable()

```bash
panel serve plot.py --dev

Recommended Plot Types

推荐图表类型

line - Line plots for time series and continuous data scatter - Scatter plots for exploring relationships between variables bar - Bar charts for categorical comparisons hist - Histograms for distribution analysis area - Area plots for stacked or filled visualizations
line - 用于时间序列和连续数据的折线图 scatter - 用于探索变量间关系的散点图 bar - 用于分类比较的柱状图 hist - 用于分布分析的直方图 area - 用于堆叠或填充可视化的面积图

Workflows

工作流程

Lookup additional information

查询额外信息

  • If the HoloViz MCP server tools are available, DO use them:
    search
    (documentation),
    hvplot_list
    (available plot types),
    hvplot_get
    (docstrings and signatures),
    skill_get
    (best-practice skills).
  • If MCP tools are not available but the
    holoviz-mcp
    CLI is installed (also available as
    hv
    ), use the equivalent CLI commands:
    holoviz-mcp search
    ,
    holoviz-mcp hvplot list
    ,
    holoviz-mcp hvplot get
    .
  • If neither is available, DO search the web. For example searching the hvplot website for
    streaming
    related information via https://hvplot.holoviz.org/en/docs/latest/search.html?q=streaming url.
  • 如果HoloViz MCP服务器工具可用,请使用它们:
    search
    (文档搜索)、
    hvplot_list
    (可用图表类型)、
    hvplot_get
    (文档字符串和签名)、
    skill_get
    (最佳实践技能)。
  • 如果MCP工具不可用但已安装
    holoviz-mcp
    CLI(也可通过
    hv
    命令调用),请使用对应的CLI命令:
    holoviz-mcp search
    holoviz-mcp hvplot list
    holoviz-mcp hvplot get
  • 如果以上都不可用,请通过网络搜索。例如通过https://hvplot.holoviz.org/en/docs/latest/search.html?q=streaming 链接在hvplot官网搜索与
    streaming
    相关的信息。

Test the app with pytest

用pytest测试应用

DO add tests to the
tests
folder and run them with
pytest tests/path/to/test_file.py
.
  • DO separate data extraction and transformation from plotting code.
  • DO fix any test errors and rerun the tests
  • DO run the tests and fix errors before displaying or serving the plots
请将测试代码添加到
tests
文件夹,并通过
pytest tests/path/to/test_file.py
运行测试。
  • 请将数据提取、转换代码与绘图代码分离。
  • 请修复所有测试错误并重新运行测试
  • 请在显示或部署图表前运行测试并修复错误

Test the app manually with panel serve

用panel serve手动测试应用

DO always start and keep running a development server
panel serve path_to_file.py --dev --show
with hot reload while developing!
  • Due to
    --show
    flag, a browser tab will automatically open showing your app.
  • Due to
    --dev
    flag, the panel server and app will automatically reload if you change the code.
  • The app will be served at http://localhost:5006/.
  • DO make sure the correct virtual environment is activated before serving the app.
  • DO fix any errors that show up in the terminal. Consider adding new tests to ensure they don't happen again.
  • DON'T stop or restart the server after changing the code. The app will automatically reload.
  • If you see 'Cannot start Bokeh server, port 5006 is already in use' in the terminal, DO serve the app on another port with
    --port {port-number}
    flag.
  • DO remind the user to test the plot on multiple screen sizes (desktop, tablet, mobile)
  • DON'T use legacy
    --autoreload
    flag
  • DON't run
    python path_to_file.py
    to test or serve the app.
  • DO use
    pn.Column, pn.Tabs, pn.Accordion
    to layout multiple plots
  • If you close the server to run other commands DO remember to restart it.
开发期间,请始终启动并保持运行带热重载的开发服务器:
panel serve path_to_file.py --dev --show
  • 由于
    --show
    参数,浏览器会自动打开一个标签页显示你的应用。
  • 由于
    --dev
    参数,当你修改代码时,panel服务器和应用会自动重载。
  • 应用将部署在http://localhost:5006/。
  • 请确保在启动应用前激活了正确的虚拟环境。
  • 请修复终端中出现的所有错误。考虑添加新测试以避免再次出现相同错误。
  • 修改代码后无需停止或重启服务器,应用会自动重载。
  • 如果终端中出现'Cannot start Bokeh server, port 5006 is already in use',请使用
    --port {port-number}
    参数在其他端口部署应用。
  • 请提醒用户在多种屏幕尺寸(桌面、平板、移动设备)上测试图表
  • 不要使用旧版
    --autoreload
    参数
  • 不要使用
    python path_to_file.py
    测试或部署应用。
  • 请使用
    pn.Column, pn.Tabs, pn.Accordion
    布局多个图表
  • 如果为执行其他命令关闭了服务器,请记得重启它。