plotly
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePlotly
Plotly
Python graphing library for creating interactive, publication-quality visualizations with 40+ chart types.
一款用于Python的绘图库,可创建具有出版级质量的交互式可视化内容,支持40余种图表类型。
Quick Start
快速入门
Install Plotly:
bash
uv pip install plotlyBasic usage with Plotly Express (high-level API):
python
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()安装Plotly:
bash
uv pip install plotly使用Plotly Express(高层API)的基础用法:
python
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()Choosing Between APIs
API选择指南
Use Plotly Express (px)
使用Plotly Express(px)
For quick, standard visualizations with sensible defaults:
- Working with pandas DataFrames
- Creating common chart types (scatter, line, bar, histogram, etc.)
- Need automatic color encoding and legends
- Want minimal code (1-5 lines)
See reference/plotly-express.md for complete guide.
适用于以下场景:快速创建具有合理默认配置的标准可视化内容
- 处理pandas DataFrames数据
- 创建常见图表类型(散点图、折线图、柱状图、直方图等)
- 需要自动颜色编码和图例
- 希望用最少代码实现(1-5行)
完整指南请查看reference/plotly-express.md。
Use Graph Objects (go)
使用Graph Objects(go)
For fine-grained control and custom visualizations:
- Chart types not in Plotly Express (3D mesh, isosurface, complex financial charts)
- Building complex multi-trace figures from scratch
- Need precise control over individual components
- Creating specialized visualizations with custom shapes and annotations
See reference/graph-objects.md for complete guide.
Note: Plotly Express returns graph objects Figure, so you can combine approaches:
python
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适用于以下场景:需要精细化控制和定制可视化内容
- 创建Plotly Express不支持的图表类型(3D网格图、等值面图、复杂金融图表)
- 从零开始构建复杂的多轨迹图表
- 需要对单个组件进行精确控制
- 创建带有自定义形状和注释的专用可视化内容
完整指南请查看reference/graph-objects.md。
注意: Plotly Express返回的是graph objects类型的Figure对象,因此你可以结合两种方式使用:
python
fig = px.scatter(df, x='x', y='y')
fig.update_layout(title='Custom Title') # 在px生成的图表上使用go的方法
fig.add_hline(y=10) # 添加形状Core Capabilities
核心功能
1. Chart Types
1. 图表类型
Plotly supports 40+ chart types organized into categories:
Basic Charts: scatter, line, bar, pie, area, bubble
Statistical Charts: histogram, box plot, violin, distribution, error bars
Scientific Charts: heatmap, contour, ternary, image display
Financial Charts: candlestick, OHLC, waterfall, funnel, time series
Maps: scatter maps, choropleth, density maps (geographic visualization)
3D Charts: scatter3d, surface, mesh, cone, volume
Specialized: sunburst, treemap, sankey, parallel coordinates, gauge
For detailed examples and usage of all chart types, see reference/chart-types.md.
Plotly支持40余种图表类型,分为以下类别:
基础图表: 散点图、折线图、柱状图、饼图、面积图、气泡图
统计图表: 直方图、箱线图、小提琴图、分布图、误差棒
科学图表: 热力图、等高线图、三元图、图像展示
金融图表: K线图、OHLC图、瀑布图、漏斗图、时间序列图
地图: 散点地图、分级统计图(choropleth)、密度地图(地理可视化)
3D图表: 3D散点图、曲面图、网格图、锥图、体积图
专用图表: 旭日图、树状图、桑基图、平行坐标图、仪表盘
所有图表类型的详细示例和用法请查看reference/chart-types.md。
2. Layouts and Styling
2. 布局与样式
Subplots: Create multi-plot figures with shared axes:
python
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)Templates: Apply coordinated styling:
python
fig = px.scatter(df, x='x', y='y', template='plotly_dark')子图: 创建带有共享坐标轴的多图组合:
python
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)模板: 应用统一的样式配置:
python
fig = px.scatter(df, x='x', y='y', template='plotly_dark')Built-in: plotly_white, plotly_dark, ggplot2, seaborn, simple_white
内置模板:plotly_white, plotly_dark, ggplot2, seaborn, simple_white
**Customization:** Control every aspect of appearance:
- Colors (discrete sequences, continuous scales)
- Fonts and text
- Axes (ranges, ticks, grids)
- Legends
- Margins and sizing
- Annotations and shapes
For complete layout and styling options, see [reference/layouts-styling.md](reference/layouts-styling.md).
**自定义:** 控制外观的各个方面:
- 颜色(离散序列、连续刻度)
- 字体与文本
- 坐标轴(范围、刻度、网格)
- 图例
- 边距与尺寸
- 注释与形状
完整的布局和样式选项请查看[reference/layouts-styling.md](reference/layouts-styling.md)。3. Interactivity
3. 交互性
Built-in interactive features:
- Hover tooltips with customizable data
- Pan and zoom
- Legend toggling
- Box/lasso selection
- Rangesliders for time series
- Buttons and dropdowns
- Animations
python
undefined内置的交互功能:
- 可自定义数据的悬停提示框
- 平移与缩放
- 图例切换
- 框选/套索选择
- 时间序列的范围滑块
- 按钮与下拉菜单
- 动画效果
python
undefinedCustom hover template
自定义悬停模板
fig.update_traces(
hovertemplate='<b>%{x}</b><br>Value: %{y:.2f}<extra></extra>'
)
fig.update_traces(
hovertemplate='<b>%{x}</b><br>Value: %{y:.2f}<extra></extra>'
)
Add rangeslider
添加范围滑块
fig.update_xaxes(rangeslider_visible=True)
fig.update_xaxes(rangeslider_visible=True)
Animations
动画效果
fig = px.scatter(df, x='x', y='y', animation_frame='year')
For complete interactivity guide, see [reference/export-interactivity.md](reference/export-interactivity.md).fig = px.scatter(df, x='x', y='y', animation_frame='year')
完整的交互功能指南请查看[reference/export-interactivity.md](reference/export-interactivity.md)。4. Export Options
4. 导出选项
Interactive HTML:
python
fig.write_html('chart.html') # Full standalone
fig.write_html('chart.html', include_plotlyjs='cdn') # Smaller fileStatic Images (requires kaleido):
bash
uv pip install kaleidopython
fig.write_image('chart.png') # PNG
fig.write_image('chart.pdf') # PDF
fig.write_image('chart.svg') # SVGFor complete export options, see reference/export-interactivity.md.
交互式HTML:
python
fig.write_html('chart.html') # 完整独立文件
fig.write_html('chart.html', include_plotlyjs='cdn') # 更小的文件体积静态图片(需要安装kaleido):
bash
uv pip install kaleidopython
fig.write_image('chart.png') # PNG格式
fig.write_image('chart.pdf') # PDF格式
fig.write_image('chart.svg') # SVG格式完整的导出选项请查看reference/export-interactivity.md。
Common Workflows
常见工作流
Scientific Data Visualization
科学数据可视化
python
import plotly.express as pxpython
import plotly.express as pxScatter plot with trendline
带趋势线的散点图
fig = px.scatter(df, x='temperature', y='yield', trendline='ols')
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')
fig = px.imshow(correlation_matrix, text_auto=True, color_continuous_scale='RdBu')
3D surface plot
3D曲面图
import plotly.graph_objects as go
fig = go.Figure(data=[go.Surface(z=z_data, x=x_data, y=y_data)])
undefinedimport plotly.graph_objects as go
fig = go.Figure(data=[go.Surface(z=z_data, x=x_data, y=y_data)])
undefinedStatistical Analysis
统计分析
python
undefinedpython
undefinedDistribution comparison
分布对比
fig = px.histogram(df, x='values', color='group', marginal='box', nbins=30)
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')
fig = px.box(df, x='category', y='value', points='all')
Violin plot
小提琴图
fig = px.violin(df, x='group', y='measurement', box=True)
undefinedfig = px.violin(df, x='group', y='measurement', box=True)
undefinedTime Series and Financial
时间序列与金融
python
undefinedpython
undefinedTime series with rangeslider
带范围滑块的时间序列图
fig = px.line(df, x='date', y='price')
fig.update_xaxes(rangeslider_visible=True)
fig = px.line(df, x='date', y='price')
fig.update_xaxes(rangeslider_visible=True)
Candlestick chart
K线图
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']
)])
undefinedimport 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']
)])
undefinedMulti-Plot Dashboards
多图仪表板
python
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)python
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)Integration with Dash
与Dash集成
For interactive web applications, use Dash (Plotly's web app framework):
bash
uv pip install dashpython
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_server(debug=True)如需创建交互式Web应用,请使用Dash(Plotly的Web应用框架):
bash
uv pip install dashpython
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_server(debug=True)Reference Files
参考文档
- plotly-express.md - High-level API for quick visualizations
- graph-objects.md - Low-level API for fine-grained control
- chart-types.md - Complete catalog of 40+ chart types with examples
- layouts-styling.md - Subplots, templates, colors, customization
- export-interactivity.md - Export options and interactive features
- plotly-express.md - 用于快速可视化的高层API指南
- graph-objects.md - 用于精细化控制的底层API指南
- chart-types.md - 40余种图表类型的完整目录及示例
- layouts-styling.md - 子图、模板、颜色与自定义配置
- export-interactivity.md - 导出选项与交互式功能
Additional Resources
额外资源
- Official documentation: https://plotly.com/python/
- API reference: https://plotly.com/python-api-reference/
- Community forum: https://community.plotly.com/