Plotly.py 极坐标图(Polar Chart)完全指南:从 Plotly Express 到 go.Scatterpolar
Plotly.py 极坐标图(Polar Chart)完全指南:从 Plotly Express 到 go.Scatterpolar
本指南以 Plotly.py 官方文档 doc/python/polar-chart.md 为核心骨架,系统讲解如何在 Python 中绘制极坐标图(Polar Chart)。你将掌握通过高层接口 px.scatter_polar / px.line_polar 快速绘图,以及通过底层 go.Scatterpolar、go.Barpolar、go.Scatterpolargl 精细控制扇形(sector)、角度方向(direction)、类别轴、子图等高级能力,并深入理解这些参数在 Plotly.py 源码中的实际映射逻辑。
一、极坐标图基础:径向轴与角度轴
极坐标图(Polar Chart)使用**径向轴(radial axis)和角度轴(angular axis)**来呈现数据,适合表达方向、周期性或环状分布类数据。在 Plotly 中,数据点由一对坐标 (r, theta) 定义:
r:径向坐标,表示数据点到圆心的距离;theta:角度坐标,表示数据点所在的方位角。theta最常见的是数值型(角度),但也可以是类别型字符串(如风向分类),此时角度轴自动按类别均匀分布。
Plotly.py 提供了两条绘图路径:高层接口 Plotly Express(px.scatter_polar、px.line_polar、px.bar_polar)和底层接口 graph_objects(go.Scatterpolar、go.Barpolar、go.Scatterpolargl)。
二、用 Plotly Express 快速绘制极坐标图
Plotly Express 是 Plotly 的高层接口,支持多种数据类型输入 且易于定制样式。绘制极坐标散点图时,径向与角度坐标分别由 r 和 theta 参数给出。
2.1 基础极坐标散点图
以下示例使用 Plotly 内置的风向数据集(px.data.wind()),direction 列为类别型角度数据,frequency 列为频率值:
import plotly.express as px
df = px.data.wind()
fig = px.scatter_polar(df, r="frequency", theta="direction")
fig.show()
theta 列是类别(风向分类),但数值型角度数据同样支持,且是更常见的用法。
2.2 用多个维度编码数据
wind 数据集中,"strength" 列对应风的强度等级,每一组(方向、强度)组合都有一个频率值。下面的例子同时用 color、symbol、size 三个通道编码数据:
import plotly.express as px
df = px.data.wind()
fig = px.scatter_polar(df, r="frequency", theta="direction",
color="strength", symbol="strength", size="frequency",
color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()
color="strength":按强度着色,配合color_discrete_sequence=px.colors.sequential.Plasma_r使用 Plasma 色阶的反向序列;symbol="strength":按强度切换标记符号;size="frequency":按频率值缩放标记大小。
2.3 极坐标折线图
折线形式的极坐标图使用 px.line_polar。line_close=True 表示首尾相连闭合图形;template="plotly_dark" 使用深色主题模板:
import plotly.express as px
df = px.data.wind()
fig = px.line_polar(df, r="frequency", theta="direction", color="strength", line_close=True,
color_discrete_sequence=px.colors.sequential.Plasma_r,
template="plotly_dark",)
fig.show()
若需进一步深入风向玫瑰图(wind rose)的可视化,可参考仓库中的 wind-rose-charts 指南。
2.4 控制角度范围、起始角与旋转方向
px.scatter_polar 还支持只绘制部分圆周:range_theta 限定角度显示范围(相当于底层 layout 中的 sector),start_angle 控制角度轴 0° 的起始位置,direction 控制角度增长方向:
import plotly.express as px
fig = px.scatter_polar(r=range(0,90,10), theta=range(0,90,10),
range_theta=[0,90], start_angle=0, direction="counterclockwise")
fig.show()
2.5 px 极坐标参数一览(来自源码签名)
从 plotly/express/_chart_types.py 的源码签名可以确认,scatter_polar 与 line_polar 支持的核心参数如下:
| 参数 | 默认值 | 说明 |
|---|---|---|
r / theta |
None |
径向 / 角度坐标列名或数组 |
color / symbol / size |
None |
颜色 / 符号 / 大小编码通道 |
direction |
"clockwise" |
角度增长方向:"clockwise" 或 "counterclockwise" |
start_angle |
90 |
角度轴 0° 的起始位置(默认指向正上方) |
range_r |
None |
径向轴显示范围,如 [0, 5] |
range_theta |
None |
角度轴显示范围(仅绘制部分圆环),对应底层 sector |
log_r |
False |
径向轴是否使用对数刻度 |
line_close(仅 line_polar) |
False |
折线是否首尾闭合 |
line_dash(仅 line_polar) |
None |
线型编码通道 |
markers(仅 line_polar) |
False |
折线上是否同时绘制标记点 |
render_mode |
"auto" |
"auto" / "svg" / "webgl",大数据量时自动切换 WebGL |
template / title / width / height |
None |
常规布局参数 |
2.6 源码视角:px 参数如何映射到底层 layout
scatter_polar / line_polar 内部均调用 make_figure(args=locals(), constructor=go.Scatterpolar) 构造图形(见 plotly/express/_chart_types.py)。真正完成极坐标轴配置的是 plotly/express/_core.py 中的 configure_polar_axes:
patch = dict(
angularaxis=dict(direction=args["direction"], rotation=args["start_angle"]),
radialaxis=dict(),
)
...
if args["log_r"]:
radialaxis["type"] = "log"
...
if args["range_theta"]:
patch["sector"] = args["range_theta"]
fig.update_polars(patch)
可以清晰地看到映射关系:direction → polar.angularaxis.direction,start_angle → polar.angularaxis.rotation,range_theta → polar.sector,range_r → polar.radialaxis.range,log_r → polar.radialaxis.type = "log"(此时 range_r 会被取以 10 为底的对数后再写入)。理解这层映射,就能在 graph_objects 中精确复刻 px 的效果。
三、用 go.Scatterpolar 绘制底层极坐标图
当 Plotly Express 无法满足需求时,可以直接使用 plotly.graph_objects 中的 go.Scatterpolar。其全部可选属性定义在 plotly/graph_objs/_scatterpolar.py 的 _valid_props 中,包括 r、theta、thetaunit、mode、fill、line、marker、subplot、dr、dtheta、r0、theta0 等。
3.1 基础极坐标散点图
import plotly.graph_objects as go
fig = go.Figure(data=
go.Scatterpolar(
r = [0.5,1,2,2.5,3,4],
theta = [35,70,120,155,205,240],
mode = 'markers',
))
fig.update_layout(showlegend=False)
fig.show()
3.2 极坐标折线图(Line Polar Chart)
以下示例从 Plotly 公开数据集(polar_dataset.csv)读取数据,在一个图中叠加三条折线(Figure 8、Cardioid 心形线、Hypercardioid),通过 mode='lines'、line_color 区分:
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/polar_dataset.csv")
fig = go.Figure()
fig.add_trace(go.Scatterpolar(
r = df['x1'],
theta = df['y'],
mode = 'lines',
name = 'Figure 8',
line_color = 'peru'
))
fig.add_trace(go.Scatterpolar(
r = df['x2'],
theta = df['y'],
mode = 'lines',
name = 'Cardioid',
line_color = 'darkviolet'
))
fig.add_trace(go.Scatterpolar(
r = df['x3'],
theta = df['y'],
mode = 'lines',
name = 'Hypercardioid',
line_color = 'deepskyblue'
))
fig.update_layout(
title = 'Mic Patterns',
showlegend = False
)
fig.show()
3.3 极坐标柱状图(Polar Bar Chart)
go.Barpolar 用扇形柱(而非笛卡尔矩形柱)表示数据,a.k.a "用几行代码画出 matplotlib logo"。柱的径向长度由 r 决定,角度位置由 theta 决定,width 控制每根柱张开的角宽,marker_color、marker_line_color、marker_line_width 控制填充色、描边色与描边宽度:
import plotly.graph_objects as go
fig = go.Figure(go.Barpolar(
r=[3.5, 1.5, 2.5, 4.5, 4.5, 4, 3],
theta=[65, 15, 210, 110, 312.5, 180, 270],
width=[20,15,10,20,15,30,15,],
marker_color=["#E4FF87", '#709BFF', '#709BFF', '#FFAA70', '#FFAA70', '#FFDF70', '#B6FFB4'],
marker_line_color="black",
marker_line_width=2,
opacity=0.8
))
fig.update_layout(
template=None,
polar = dict(
radialaxis = dict(range=[0, 5], showticklabels=False, ticks=''),
angularaxis = dict(showticklabels=False, ticks='')
)
)
fig.show()
这里通过 polar.radialaxis(range=<a href="https://link.gitcode.com/i/8dad08409b4e14d7057d633bcb28d31a" target="_blank">0, 5]、隐藏刻度标签)与 polar.angularaxis(隐藏刻度标签)简化了坐标轴,突出柱体本身。Barpolar 的完整属性列表见 [plotly/graph_objs/_barpolar.py,其中 base 用于设置柱的基线(按径向轴单位),offset 用于角度方向偏移,thetaunit 决定 theta 的输入单位。
3.4 类别型极坐标图(Categorical Polar Chart)
极坐标轴天然支持类别数据:角度轴可以是类别,径向轴也可以是类别。下面用 make_subplots 创建 2×2 的极坐标子图,分别演示 4 种类别轴配置:
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=2, specs=[[{'type': 'polar'}]*2]*2)
fig.add_trace(go.Scatterpolar(
name = "angular categories",
r = [5, 4, 2, 4, 5],
theta = ["a", "b", "c", "d", "a"],
), 1, 1)
fig.add_trace(go.Scatterpolar(
name = "radial categories",
r = ["a", "b", "c", "d", "b", "f", "a"],
theta = [1, 4, 2, 1.5, 1.5, 6, 5],
thetaunit = "radians",
), 1, 2)
fig.add_trace(go.Scatterpolar(
name = "angular categories (w/ categoryarray)",
r = [5, 4, 2, 4, 5],
theta = ["a", "b", "c", "d", "a"],
), 2, 1)
fig.add_trace(go.Scatterpolar(
name = "radial categories (w/ category descending)",
r = ["a", "b", "c", "d", "b", "f", "a", "a"],
theta = [45, 90, 180, 200, 300, 15, 20, 45],
), 2, 2)
fig.update_traces(fill='toself')
fig.update_layout(
polar = dict(
radialaxis_angle = -45,
angularaxis = dict(
direction = "clockwise",
period = 6)
),
polar2 = dict(
radialaxis = dict(
angle = 180,
tickangle = -180 # so that tick labels are not upside down
)
),
polar3 = dict(
sector = [80, 400],
radialaxis_angle = -45,
angularaxis_categoryarray = ["d", "a", "c", "b"]
),
polar4 = dict(
radialaxis_categoryorder = "category descending",
angularaxis = dict(
thetaunit = "radians",
dtick = 0.3141592653589793
))
)
fig.show()
本例涉及的关键概念:
thetaunit:设置theta输入值的单位,枚举值为<a href="https://link.gitcode.com/i/9a9e4234715cdffd81467d3581b8bc01" target="_blank">'radians', 'degrees', 'gradians'](弧度 / 度 / 百分度),见 [plotly/graph_objs/_scatterpolar.py。它仅在角度轴为线性类型时生效;angularaxis.period:类别角度轴的周期,示例中设为 6,使类别数据按 6 个等分角排列;angularaxis_categoryarray:显式指定角度类别的排列顺序(子图 polar3 中改为["d", "a", "c", "b"]);radialaxis_categoryorder:径向类别轴的排序方式,示例使用"category descending"(类别降序);radialaxis_angle/radialaxis.angle:径向轴自身的指向角度,用于旋转整组类别;sector = [80, 400]:仅显示 80°~400° 的扇形区域;fill='toself':让折线填充成封闭多边形区域。
3.5 扇形区域(Polar Chart Sector)
通过 layout 中的 polar.sector 可以只显示圆周的某一段。以下示例让两个完全相同的 trace 分列左右,仅在第一个子图上设置 sector = [150,210]:
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'polar'}]*2])
fig.add_trace(go.Scatterpolar(), 1, 1)
fig.add_trace(go.Scatterpolar(), 1, 2)
# Same data for the two Scatterpolar plots, we will only change the sector in the layout
fig.update_traces(mode = "lines+markers",
r = [1,2,3,4,5],
theta = [0,90,180,360,0],
line_color = "magenta",
marker = dict(
color = "royalblue",
symbol = "square",
size = 8
))
# The sector is [0, 360] by default, we update it for the first plot only
fig.update_layout(
showlegend = False,
polar = dict(# setting parameters for the second plot would be polar2=dict(...)
sector = [150,210],
))
fig.show()
注意:sector 的默认范围是 [0, 360]。在多子图场景下,第一个子图的布局键为 polar,后续子图依次为 polar2、polar3、polar4(本例中若需修改第二个子图,应使用 polar2 = dict(...))。
3.6 角度方向与起始角(Polar Chart Directions)
角度轴有两个关键属性:direction(角度增长方向:"clockwise" 顺时针 或 "counterclockwise" 逆时针)与 rotation(角度轴 0° 的起始位置)。下例左右两个子图使用相同数据,仅角度方向不同:
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'polar'}, {'type': 'polar'}]])
r = [1,2,3,4,5]
theta = [0,90,180,360,0]
fig.add_trace(go.Scatterpolar(), 1, 1)
fig.add_trace(go.Scatterpolar(), 1, 2)
# Same data for the two Scatterpolar plots, we will only change the direction in the layout
fig.update_traces(r= r, theta=theta,
mode="lines+markers", line_color='indianred',
marker=dict(color='lightslategray', size=8, symbol='square'))
fig.update_layout(
showlegend = False,
polar = dict(
radialaxis_tickfont_size = 8,
angularaxis = dict(
tickfont_size=8,
rotation=90, # start position of angular axis
direction="counterclockwise"
)
),
polar2 = dict(
radialaxis_tickfont_size = 8,
angularaxis = dict(
tickfont_size = 8,
rotation = 90,
direction = "clockwise"
),
))
fig.show()
rotation=90 表示角度轴 0° 位于 90° 位置(正上方为默认起始位),配合 direction 即可完全控制角度的起始与增长方向——这正是 px.scatter_polar(start_angle=..., direction=...) 在底层所做的配置。
3.7 WebGL 极坐标图(go.Scatterpolargl)
当数据点数量巨大时,可使用 go.Scatterpolargl——它基于 WebGL 绘图引擎,借助 GPU 加速渲染,属性集与 Scatterpolar 基本一致(见 plotly/graph_objs/_scatterpolargl.py)。下面的例子绘制霍布斯-皮尔逊试验(Hobbs-Pearson Trials)的 6 组数据:
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/hobbs-pearson-trials.csv")
fig = go.Figure()
fig.add_trace(go.Scatterpolargl(
r = df.trial_1_r,
theta = df.trial_1_theta,
name = "Trial 1",
marker=dict(size=15, color="mediumseagreen")
))
fig.add_trace(go.Scatterpolargl(
r = df.trial_2_r,
theta = df.trial_2_theta,
name = "Trial 2",
marker=dict(size=20, color="darkorange")
))
fig.add_trace(go.Scatterpolargl(
r = df.trial_3_r,
theta = df.trial_3_theta,
name = "Trial 3",
marker=dict(size=12, color="mediumpurple")
))
fig.add_trace(go.Scatterpolargl(
r = df.trial_4_r,
theta = df.trial_4_theta,
name = "Trial 4",
marker=dict(size=22, color = "magenta")
))
fig.add_trace(go.Scatterpolargl(
r = df.trial_5_r,
theta = df.trial_5_theta,
name = "Trial 5",
marker=dict(size=19, color = "limegreen")
))
fig.add_trace(go.Scatterpolargl(
r = df.trial_6_r,
theta = df.trial_6_theta,
name = "Trial 6",
marker=dict(size=10, color = "gold")
))
# Common parameters for all traces
fig.update_traces(mode="markers", marker=dict(line_color='white', opacity=0.7))
fig.update_layout(
title = "Hobbs-Pearson Trials",
font_size = 15,
showlegend = False,
polar = dict(
bgcolor = "rgb(223, 223, 223)",
angularaxis = dict(
linewidth = 3,
showline=True,
linecolor='black'
),
radialaxis = dict(
side = "counterclockwise",
showline = True,
linewidth = 2,
gridcolor = "white",
gridwidth = 2,
)
),
paper_bgcolor = "rgb(223, 223, 223)"
)
fig.show()
本例还展示了极坐标轴的深度样式定制:polar.bgcolor 设置极坐标区域背景色,paper_bgcolor 设置整张画布背景色;angularaxis.showline/linewidth/linecolor 控制角度轴的轴线;radialaxis.side 控制径向轴刻度标签所在侧(此处为 "counterclockwise"),gridcolor/gridwidth 控制径向网格线样式。
四、极坐标子图(Polar Chart Subplots)
make_subplots 通过 specs 声明子图类型为 {'type': 'polar'},即可在网格中排布多个极坐标图。子图编号遵循 polar、polar2、polar3、polar4 的布局命名规则,trace 可通过 subplot="polar2" 等参数显式指定所属子图:
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=2, specs=[[{'type': 'polar'}]*2]*2)
fig.add_trace(go.Scatterpolar(
r = [1, 2, 3],
theta = [50, 100, 200],
marker_symbol = "square"
), 1, 1)
fig.add_trace(go.Scatterpolar(
r = [1, 2, 3],
theta = [1, 2, 3],
thetaunit = "radians"
), 1, 1)
fig.add_trace(go.Scatterpolar(
r = ["a", "b", "c", "b"],
theta = ["D", "C", "B", "A"],
subplot = "polar2"
), 1, 2)
fig.add_trace(go.Scatterpolar(
r = [50, 300, 900],
theta = [0, 90, 180],
subplot = "polar3"
), 2, 1)
fig.add_trace(go.Scatterpolar(
mode = "lines",
r = [3, 3, 4, 3],
theta = [0, 45, 90, 270],
fill = "toself",
subplot = "polar4"
), 2, 2)
fig.update_layout(
polar = dict(
radialaxis_range = [1, 4],
angularaxis_thetaunit = "radians"
),
polar3 = dict(
radialaxis = dict(type = "log", tickangle = 45),
sector = [0, 180]
),
polar4 = dict(
radialaxis = dict(visible = False, range = [0, 6])),
showlegend = False
)
fig.show()
子图示例覆盖了几种常见组合:
- 同一子图叠加多个 trace:第 (1,1) 子图同时绘制角度制与弧度制(
thetaunit="radians")两组数据; - 类别角度 + 类别径向:第 (1,2) 子图的
r与theta都是类别字符串; - 对数径向轴 + 扇形裁剪:第 (2,1) 子图通过
radialaxis.type = "log"使用对数径向轴、sector = [0, 180]只显示半圆; - 隐藏径向轴:第 (2,2) 子图通过
radialaxis.visible = False隐藏径向轴线,仅保留数据图形; - 布局中可直接使用扁平写法,如
radialaxis_range、angularaxis_thetaunit(等价于嵌套的dict(radialaxis=dict(range=...)))。
五、常用属性速查与底层实现提示
5.1 Scatterpolar 核心属性
依据 plotly/graph_objs/_scatterpolar.py 的 _valid_props,常用属性包括:
| 属性 | 说明 |
|---|---|
r / theta |
径向 / 角度坐标数组 |
mode |
"markers" / "lines" / "lines+markers" / "text" 等组合 |
thetaunit |
theta 输入单位:radians / degrees / gradians,仅线性角度轴生效 |
fill |
折线填充方式,如 "toself"(闭合填充) |
line / marker |
线条与标记样式(颜色、宽度、符号、大小) |
subplot |
所属子图名,如 "polar2" |
dr / dtheta |
径向 / 角度坐标的步长,配合 r0 / theta0 支持等间隔生成坐标(见 源码) |
r0 / theta0 |
径向 / 角度坐标的起始值(见 源码 与 theta0) |
connectgaps |
是否连接数据中的 nan 缺口 |
5.2 polar layout 常用配置
| 配置项 | 说明 |
|---|---|
polar.sector |
显示的角度扇形范围,如 [150, 210],默认 [0, 360] |
polar.angularaxis.direction |
角度增长方向:"clockwise" / "counterclockwise" |
polar.angularaxis.rotation |
角度轴 0° 起始位置 |
polar.angularaxis.period |
类别角度轴的周期 |
polar.angularaxis.categoryarray |
类别显式排序 |
polar.radialaxis.range / type |
径向轴范围 / 轴类型("log" 等) |
polar.radialaxis.categoryorder |
径向类别排序,如 "category descending" |
polar.bgcolor |
极坐标区域背景色 |
5.3 从 px 到 go 的等价写法
阅读 plotly/express/_core.py 中的 configure_polar_axes 后可以发现,所有 px 极坐标参数最终都落到 layout 的 polar 域中,因此以下两种写法等价:
# 方式一:Plotly Express
fig = px.scatter_polar(r=[1,2,3], theta=[0,90,180],
range_theta=[0,180], start_angle=0, direction="counterclockwise")
# 方式二:graph_objects 手动配置
import plotly.graph_objects as go
fig = go.Figure(go.Scatterpolar(r=[1,2,3], theta=[0,90,180]))
fig.update_layout(polar=dict(
sector=[0, 180],
angularaxis=dict(rotation=0, direction="counterclockwise"),
))
六、参考与延伸阅读
- 官方示例 polar-chart.md 是本文的原始素材,含全部可运行代码;
- 风向玫瑰图进阶:仓库内的 wind-rose-charts.md;
- Plotly Express 入门:plotly-express.md;参数输入说明见 px-arguments.md;样式定制见 styling-plotly-express.md;
- graph_objects 基础:graph-objects.md;
px.scatter_polar/px.line_polar的完整函数签名与文档字符串:plotly/express/_chart_types.py;go.Scatterpolar/go.Barpolar/go.Scatterpolargl的全部属性定义与说明:plotly/graph_objs/_scatterpolar.py、plotly/graph_objs/_barpolar.py、plotly/graph_objs/_scatterpolargl.py。
极坐标图是表达方向、周期性数据的利器:遇到风向玫瑰图、麦克风指向性图、雷达试验数据这类场景,优先用 px.scatter_polar / px.line_polar 快速出图;需要多子图、类别轴重排、扇形裁剪或对数径向轴时,再切换到 go.Scatterpolar 与 polar 布局精细调校;而面对海量点数据,go.Scatterpolargl 的 WebGL 渲染则是不二之选。