pyecharts设置桑基图节点颜色
时间: 2023-09-25 09:11:28 浏览: 138
JavaFX 绘制桑基图(SankeyDiagram)
要设置桑基图节点颜色,可以使用 `node_color` 参数。具体代码如下:
```python
from pyecharts import options as opts
from pyecharts.charts import Sankey
nodes = [{"name": "A"}, {"name": "B"}, {"name": "C"}, {"name": "D"}]
links = [
{"source": "A", "target": "B", "value": 10},
{"source": "B", "target": "C", "value": 15},
{"source": "C", "target": "D", "value": 20}
]
sankey = (
Sankey()
.add(
"sankey",
nodes=nodes,
links=links,
node_gap=20,
node_width=25,
line_opacity=0.5,
node_color="#5ab1ef"
)
.set_global_opts(title_opts=opts.TitleOpts(title="Sankey Diagram"))
)
sankey.render("sankey.html")
```
在上述代码中,`node_color` 参数设置为 `"#5ab1ef"`,即节点颜色为蓝色。可以根据需要设置不同的颜色。
同时,如果想要为不同的节点设置不同的颜色,可以在 `nodes` 列表中为每个节点指定颜色,然后在 `node_color` 参数中使用 `lambda` 函数返回对应节点的颜色。具体代码如下:
```python
from pyecharts import options as opts
from pyecharts.charts import Sankey
nodes = [
{"name": "A", "itemStyle": {"color": "#f7f7f7"}},
{"name": "B", "itemStyle": {"color": "#cdcdcd"}},
{"name": "C", "itemStyle": {"color": "#8f8f8f"}},
{"name": "D", "itemStyle": {"color": "#1f1f1f"}}
]
links = [
{"source": "A", "target": "B", "value": 10},
{"source": "B", "target": "C", "value": 15},
{"source": "C", "target": "D", "value": 20}
]
sankey = (
Sankey()
.add(
"sankey",
nodes=nodes,
links=links,
node_gap=20,
node_width=25,
line_opacity=0.5,
node_color=lambda node: node["itemStyle"]["color"]
)
.set_global_opts(title_opts=opts.TitleOpts(title="Sankey Diagram"))
)
sankey.render("sankey.html")
```
在上述代码中,每个节点在 `nodes` 列表中都指定了颜色,然后在 `node_color` 参数中使用 `lambda` 函数返回对应节点的颜色,这样就可以为每个节点设置不同的颜色了。
阅读全文