mcpField
A
alterlab-plotly

alterlab-plotly

github.com/alterlab-ieu数据与数据库7868 次安装5 周前更新
代码仓库

关于 alterlab-plotly

Plotly 技能面向需要交互式数据图表的 Python 用户,支持多类图形、细致样式控制及 HTML 和静态图像导出。

主要功能

  1. 0140 多种图表类型
  2. 02Plotly Express 与 Graph Objects
  3. 03缩放、悬停和动画交互
  4. 04子图布局与样式定制
  5. 05导出交互式 HTML 和静态图像

适用场景

  1. 01探索数据中的单个观测点
  2. 02制作可共享的交互式图表
  3. 03构建多图表仪表板
  4. 04导出论文或报告中的图像

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/alterlab-ieu/alterlab-academic-skills --skill alterlab-plotly

安装后在 Claude Code 中输入/alterlab-plotly确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

evals/
evals.json
references/
chart-types.md
export-interactivity.md
graph-objects.md
layouts-styling.md
plotly-express.md

详细介绍

Plotly

用于创建交互式、出版级可视化图表的 Python 绘图库,支持 40 多种图表类型。示例面向 plotly >= 6,并可在 plotly 7.1(plotly.js 4)上运行;如果要升级旧代码,请参阅下文的“Plotly 7 变更”。

何时使用此技能

当图表需要支持交互式探索或共享时,请使用此技能:

  • 悬停提示、缩放/平移、切换图例、范围滑块、下拉菜单或动画帧
  • 独立 HTML 或嵌入网页的图表,以及 Dash 仪表板
  • 可旋转的 3D 图表(surface、scatter3d、mesh、volume)
  • 读者需要检查单个数据点的探索性分析
不适用的情况
场景改用
无交互功能的静态、适合打印的图表alterlab-matplotlib
符合期刊格式的多面板图表(列宽、Okabe-Ito 调色板、显著性星号)alterlab-scientific-viz
从 DataFrame 快速绘制静态统计图表(热图、成对图、分布图)alterlab-seaborn
流程图、路径图或架构图alterlab-scientific-schematics / alterlab-mermaid

快速入门

安装 Plotly:

uv pip install plotly

使用 Plotly Express 的基本用法(高级 API):

import plotly.express as px
import pandas as pd

df = pd.DataFrame({
    'x': [1, 2, 3, 4],
    'y': [10, 11, 12, 13]
})

fig = px.scatter(df, x='x', y='y', title='My First Plot')
fig.show()

选择 API

使用 Plotly Express (px)

适用于快速创建采用合理默认设置的标准可视化图表:

  • 使用 pandas DataFrame
  • 创建常见图表类型(散点图、折线图、条形图、直方图等)
  • 需要自动进行颜色编码并生成图例
  • 希望代码尽可能精简(1-5 行)

完整指南请参阅 references/plotly-express.md。

使用 Graph Objects (go)

适用于需要精细控制和自定义可视化的场景:

  • Plotly Express 未提供的图表类型(3D 网格、等值面、复杂金融图表)
  • 从头构建包含多个迹线的复杂图表
  • 需要精确控制各个组件
  • 创建带有自定义形状和注释的专用可视化图表

完整指南请参阅 references/graph-objects.md。

注意: Plotly Express 返回图表对象 Figure,因此可以结合使用这两种方式:

fig = px.scatter(df, x='x', y='y')
fig.update_layout(title='Custom Title')  # Use go methods on px figure
fig.add_hline(y=10)                     # Add shapes

核心功能

1. 图表类型

Plotly 支持 40 多种图表类型,可分为以下类别:

基本图表: scatter、line、bar、pie、area、bubble

统计图表: histogram、box plot、violin、distribution、error bars

科学图表: heatmap、contour、ternary、image display

金融图表: candlestick、OHLC、waterfall、funnel、time series

地图: scatter maps、choropleth、density maps(地理地图,基于 MapLibre;*_mapbox 函数和迹线已在 plotly 7 中移除)

3D 图表: scatter3d、surface、mesh、cone、volume

专用图表: sunburst、treemap、sankey、parallel coordinates、gauge

所有图表类型的详细示例和用法,请参阅 references/chart-types.md。

2. 布局和样式

子图: 创建共享坐标轴的多图表图形:

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=2, cols=2, subplot_titles=('A', 'B', 'C', 'D'))
fig.add_trace(go.Scatter(x=[1, 2], y=[3, 4]), row=1, col=1)

模板: 应用协调统一的样式:

fig = px.scatter(df, x='x', y='y', template='plotly_dark')
# Built-in: plotly_white, plotly_dark, ggplot2, seaborn, simple_white

自定义: 控制外观的各个方面:

  • 颜色(离散序列、连续色阶)
  • 字体和文本
  • 坐标轴(范围、刻度、网格)
  • 图例
  • 边距和尺寸
  • 注释和形状

完整的布局和样式选项请参阅 references/layouts-styling.md。

3. 交互性

内置交互功能:

  • 可自定义数据的悬停提示
  • 平移和缩放
  • 切换图例
  • 框选/套索选择
  • 时间序列范围滑块
  • 按钮和下拉菜单
  • 动画
# Custom hover template
fig.update_traces(
    hovertemplate='<b>%{x}</b><br>Value: %{y:.2f}<extra></extra>'
)

# Add rangeslider
fig.update_xaxes(rangeslider_visible=True)

# Animations
fig = px.scatter(df, x='x', y='y', animation_frame='year')

完整的交互功能指南请参阅 references/export-interactivity.md。

4. 导出选项

交互式 HTML:

fig.write_html('chart.html')                       # Full standalone
fig.write_html('chart.html', include_plotlyjs='cdn')  # Smaller file

静态图像(需要 kaleido >= 1 和 Chrome):

uv pip install kaleido
plotly_get_chrome    # one-time: installs a Chrome build if the machine has none
fig.write_image('chart.png', scale=3)   # PNG (700x500 default size -> 2100x1500 px)
fig.write_image('chart.pdf')            # PDF
fig.write_image('chart.svg')            # SVG

如果没有 Chrome,write_image 会报错:“Kaleido requires Google Chrome to be installed”。使用 plotly.io.defaults 设置导出默认值(例如,pio.defaults.default_scale = 2);旧的 pio.kaleido.scope 设置已不存在。

如需了解完整的导出选项,请参阅 references/export-interactivity.md。

常见工作流

科学数据可视化
import plotly.express as px

# Scatter plot with trendline (trendline='ols'/'lowess' requires statsmodels:
#   uv pip install statsmodels)
fig = px.scatter(df, x='temperature', y='yield', trendline='ols')

# Heatmap from matrix
fig = px.imshow(correlation_matrix, text_auto=True, color_continuous_scale='RdBu')

# 3D surface plot
import plotly.graph_objects as go
fig = go.Figure(data=[go.Surface(z=z_data, x=x_data, y=y_data)])
统计分析
# Distribution comparison
fig = px.histogram(df, x='values', color='group', marginal='box', nbins=30)

# Box plot with all points
fig = px.box(df, x='category', y='value', points='all')

# Violin plot
fig = px.violin(df, x='group', y='measurement', box=True)
时间序列与金融
# Time series with rangeslider
fig = px.line(df, x='date', y='price')
fig.update_xaxes(rangeslider_visible=True)

# Candlestick chart
import plotly.graph_objects as go
fig = go.Figure(data=[go.Candlestick(
    x=df['date'],
    open=df['open'],
    high=df['high'],
    low=df['low'],
    close=df['close']
)])
多图表仪表板
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=('Scatter', 'Bar', 'Histogram', 'Box'),
    specs=[[{'type': 'scatter'}, {'type': 'bar'}],
           [{'type': 'histogram'}, {'type': 'box'}]]
)

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_trace(go.Bar(x=['A', 'B'], y=[1, 2]), row=1, col=2)
fig.add_trace(go.Histogram(x=data), row=2, col=1)
fig.add_trace(go.Box(y=data), row=2, col=2)

fig.update_layout(height=800, showlegend=False)

与 Dash 集成

如需构建交互式 Web 应用,请使用 Dash(Plotly 的 Web 应用框架):

uv pip install dash
import dash
from dash import dcc, html
import plotly.express as px

app = dash.Dash(__name__)

fig = px.scatter(df, x='x', y='y')

app.layout = html.Div([
    html.H1('Dashboard'),
    dcc.Graph(figure=fig)
])

app.run(debug=True)  # Dash >= 3 (current 4.x): run_server() was removed; use app.run()

Plotly 7 变更(2026 年 8 月)

Plotly 7.0 迁移到 plotly.js 4,并移除了长期弃用的 API。旧代码无法运行时:

  • px.scatter_mapbox / density_mapbox / choropleth_mapbox / line_mapbox 和 go.*mapbox 轨迹已移除 — 请改用 px.scatter_map、px.density_map、px.choropleth_map、px.line_map(MapLibre,使用 map_style=,无需令牌)。
  • 已移除弃用的 figure-factory 函数(create_annotated_heatmap、create_distplot、create_gantt、create_facet_grid、create_scatterplotmatrix、create_violin、create_candlestick、create_ohlc 等)。请改用 Plotly Express:px.imshow(z, text_auto=True)、px.histogram(..., marginal='rug')、px.timeline、px.scatter_matrix、px.violin、go.Candlestick / go.Ohlc。ff.create_dendrogram、create_quiver、create_streamline、create_table、create_trisurf 和 create_ternary_contour 仍可使用。
  • 静态导出仅支持 Kaleido >= 1(不支持 Orca),且 write_image / to_image 的 engine= 参数已移除。
  • 颜色字符串:不再支持使用 0–1 小数通道值的 rgb() / rgba() 以及 hsv();现在支持 rgba(255 0 0 / 0.5)、#ff0000aa 和 oklch() 等新格式。
  • 新增了用于矢量场的 go.Quiver 轨迹。

参考文件

其他资源

评论

支持 Markdown