pyecharts桑基图指定节点颜色
时间: 2023-09-20 18:06:17 浏览: 237
Pyecharts 中的桑基图(Sankey Diagram)可以通过设置节点样式的方式来指定节点颜色。具体步骤如下:
1. 导入所需的库和模块:
```python
from pyecharts.charts import Sankey
from pyecharts import options as opts
```
2. 创建桑基图对象:
```python
sankey = Sankey()
```
3. 设置节点样式:
```python
node_color = {"category1": "#c23531", "category2": "#2f4554", "category3": "#d48265"}
```
其中,`category1`、`category2`、`category3` 是节点的名称,`#c23531`、`#2f4554`、`#d48265` 是对应节点的颜色值。
4. 添加节点:
```python
sankey.add(
"Sankey",
nodes=["category1", "category2", "category3"],
links=[
{"source": "category1", "target": "category2", "value": 10},
{"source": "category2", "target": "category3", "value": 15},
],
node_gap=20,
label_opts=opts.LabelOpts(position="right"),
itemstyle_opts=opts.ItemStyleOpts(border_width=1, border_color="#aaa"),
linestyle_opt=opts.LineStyleOpts(
opacity=0.2, curve=0.5, type_="dotted", width=2
),
tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"),
node_width=50,
node_padding=10,
node_align="justify",
orient="vertical",
).set_global_opts(
title_opts=opts.TitleOpts(title="Sankey Diagram", subtitle="Example"),
tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"),
)
```
在 `add()` 方法中,需要设置节点的名称和节点之间的关系,即连接线。在这里,我们没有直接设置节点的颜色,而是通过 `itemstyle_opts` 参数来设置节点的样式,包括边框宽度、边框颜色等。另外,还可以通过 `node_width` 参数来设置节点的宽度,`node_padding` 参数来设置节点内边距,`node_align` 参数来设置节点的对齐方式,以及 `orient` 参数来设置桑基图的方向。
5. 渲染图表:
```python
sankey.render("sankey.html")
```
完整示例代码如下:
```python
from pyecharts.charts import Sankey
from pyecharts import options as opts
# 创建桑基图对象
sankey = Sankey()
# 设置节点样式
node_color = {"category1": "#c23531", "category2": "#2f4554", "category3": "#d48265"}
# 添加节点
sankey.add(
"Sankey",
nodes=["category1", "category2", "category3"],
links=[
{"source": "category1", "target": "category2", "value": 10},
{"source": "category2", "target": "category3", "value": 15},
],
node_gap=20,
label_opts=opts.LabelOpts(position="right"),
itemstyle_opts=opts.ItemStyleOpts(border_width=1, border_color="#aaa"),
linestyle_opt=opts.LineStyleOpts(
opacity=0.2, curve=0.5, type_="dotted", width=2
),
tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"),
node_width=50,
node_padding=10,
node_align="justify",
orient="vertical",
).set_global_opts(
title_opts=opts.TitleOpts(title="Sankey Diagram", subtitle="Example"),
tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"),
)
# 渲染图表
sankey.render("sankey.html")
```
阅读全文