pyecharts矩形树图显示数值
时间: 2023-06-10 17:09:18 浏览: 216
要在 pyecharts 的矩形树图中显示数值,可以使用 `Tooltip` 组件。具体步骤如下:
1. 导入 `Tooltip` 组件:
```python
from pyecharts import options as opts
from pyecharts.charts import Treemap
from pyecharts.commons.utils import JsCode
```
2. 设置数据并绘制矩形树图:
```python
data = [
{"value": 40, "name": "1.1"},
{"value": 20, "name": "1.2"},
{"value": 20, "name": "1.3"},
{"value": 10, "name": "1.4"},
{"value": 10, "name": "1.5"},
{"value": 20, "name": "2.1"},
{"value": 10, "name": "2.2"},
{"value": 10, "name": "2.3"},
{"value": 10, "name": "2.4"},
{"value": 10, "name": "2.5"}
]
treemap = (
Treemap()
.add("",
data,
visual_min=0,
visual_max=50,
levels=[
{"itemStyle": {"normal": {"borderColor": "#777", "borderWidth": 0, "gapWidth": 1}}, "upperLabel": {"show": False}, "label": {"show": False}},
{"itemStyle": {"normal": {"borderColor": "#555", "borderWidth": 5, "gapWidth": 1}}, "label": {"formatter": "function (params) {return params.name + ' (' + params.value + ')';}"}}
]
)
.set_global_opts(title_opts=opts.TitleOpts(title="矩形树图-显示数值"))
)
```
在 `add` 方法中,需要设置 `visual_min` 和 `visual_max` 参数,用来指定数据的最小值和最大值。同时,在 `levels` 参数中,需要设置第二层的标签的 `formatter` 属性,用来格式化显示数值。
3. 设置 Tooltip 组件并渲染图表:
```python
treemap.set_series_opts(tooltip_opts=opts.TooltipOpts(
formatter=JsCode(
"function (params) {"
"return params.treePathInfo[1].name + ' (' + params.value + ')';"
"}"
)
))
treemap.render("treemap.html")
```
在 `set_series_opts` 方法中,设置 `tooltip_opts` 参数,并设置 `formatter` 属性,用来显示当前节点的名称和数值。
完整的代码如下:
```python
from pyecharts import options as opts
from pyecharts.charts import Treemap
from pyecharts.commons.utils import JsCode
data = [
{"value": 40, "name": "1.1"},
{"value": 20, "name": "1.2"},
{"value": 20, "name": "1.3"},
{"value": 10, "name": "1.4"},
{"value": 10, "name": "1.5"},
{"value": 20, "name": "2.1"},
{"value": 10, "name": "2.2"},
{"value": 10, "name": "2.3"},
{"value": 10, "name": "2.4"},
{"value": 10, "name": "2.5"}
]
treemap = (
Treemap()
.add("",
data,
visual_min=0,
visual_max=50,
levels=[
{"itemStyle": {"normal": {"borderColor": "#777", "borderWidth": 0, "gapWidth": 1}}, "upperLabel": {"show": False}, "label": {"show": False}},
{"itemStyle": {"normal": {"borderColor": "#555", "borderWidth": 5, "gapWidth": 1}}, "label": {"formatter": "function (params) {return params.name + ' (' + params.value + ')';}"}}
]
)
.set_global_opts(title_opts=opts.TitleOpts(title="矩形树图-显示数值"))
)
treemap.set_series_opts(tooltip_opts=opts.TooltipOpts(
formatter=JsCode(
"function (params) {"
"return params.treePathInfo[1].name + ' (' + params.value + ')';"
"}"
)
))
treemap.render("treemap.html")
```
阅读全文