Pyecharats教程2——树形图表

Pyecharats教程2——树形图表

本教程旨在介绍Pyecharts中树形图表的用法
更加详细内容可以查阅文档:https://pyecharts.org/#/zh-cn/intro
图来自github图床,如果图刷不出来可能是网问题

树形表图有两类:

  • 树图


    image
  • 矩阵树图


    image

下面一次介绍这两种树形图表。

1. 树图

1.1 快速上手

示例代码:

from pyecharts import options as opts
from pyecharts.charts import Tree


data = [
    {
        "children": [
            {"name": "B"},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]


c = (
    Tree()
    .add("", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-基本示例"))
)

c.render_notebook()
image

树图节点的数据格式是字典格式。描述树节点的类为TreeItem

class TreeItem(
    # 树节点的名称,用来标识每一个节点。
    name: Optional[str] = None,

    # 节点的值,在 tooltip 中显示。
    value: Optional[Numeric] = None,

    # 该节点的样式,参考 `series_options.LabelOpts`
    label_opts: Optional[LabelOpts] = None,

    # 子节点,嵌套定义。
    children: Optional[Sequence] = None,
)

树图的类Tree

class Tree(
    # 初始化配置项,参考 `global_options.InitOpts`
    init_opts: opts.InitOpts = opts.InitOpts()
)

该类下有一个重要的函数:

def add(
    # 系列名称,用于 tooltip 的显示,legend 的图例筛选。
    series_name: str,

    # 系列数据项
    data: Sequence[Union[opts.TreeItem, dict]],

    # 树图的布局,有 正交 和 径向 两种。这里的 正交布局 就是我们通常所说的水平 和 垂直 方向,
    # 对应的参数取值为 'orthogonal' 。而 径向布局 是指以根节点为圆心,每一层节点为环,
    # 一层层向外发散绘制而成的布局,对应的参数取值为 'radial'
    layout: str = "orthogonal",

    # 标记的图形。ECharts 提供的标记类型包括 'emptyCircle', 'circle', 'rect', 'roundRect', 
    # 'triangle', 'diamond', 'pin', 'arrow', 'none'。
    symbol: types.JSFunc = "emptyCircle",

    # 标记的大小,可以设置成诸如 10 这样单一的数字,也可以用数组分开表示宽和高,
    # 例如 [20, 10] 表示标记宽为 20,高为 10。
    symbol_size: types.Union[types.JSFunc, types.Numeric, types.Sequence] = 7,

    # 树图中 正交布局 的方向,也就是说只有在 layout = 'orthogonal' 的时候,
    # 该配置项才生效。对应有 水平 方向的 从左到右,从右到左;以及垂直方向的从上到下,
    # 从下到上。取值分别为 'LR' , 'RL', 'TB', 'BT'。注意,之前的配置项值 'horizontal' 
    # 等同于 'LR', 'vertical' 等同于 'TB'。
    orient: str = "LR",

    # tree组件离容器上侧的距离。
    # top 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,
    # 也可以是 'top', 'middle', 'bottom'。
    # 如果 top 的值为'top', 'middle', 'bottom',组件会根据相应的位置自动对齐。
    pos_top: Optional[str] = None,

    # tree 组件离容器左侧的距离。
    # left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,
    # 也可以是 'left', 'center', 'right'。
    # 如果 left 的值为'left', 'center', 'right',组件会根据相应的位置自动对齐。
    pos_left: Optional[str] = None,

    # tree 组件离容器下侧的距离。
    # bottom 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    pos_bottom: Optional[str] = None,

    # tree 组件离容器右侧的距离。
    # right 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    pos_right: Optional[str] = None,

    # 折叠节点间隔,当节点过多时可以解决节点显示过杂间隔。
    collapse_interval: Numeric = 0,

    # 树图在 正交布局 下,边的形状。分别有曲线和折线两种,对应的取值是 curve 和 polyline.
    # 注意:该配置项只在 正交布局 下有效,在经向布局下的开发环境中会报错。
    edge_shape: str = "curve",

    # 正交布局下当边的形状是折线时,子树中折线段分叉的位置。
    # 这里的位置指的是分叉点与子树父节点的距离占整个子树高度的百分比。
    # 默认取值是 '50%',可以是 ['0', '100%'] 之间。
    # 注意:该配置项只有在 edgeShape = 'curve' 时才有效。
    edge_fork_position: str = "50%",

    # 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移。
    # 可以设置成 'scale' 或者 'move'。设置成 true 为都开启
    is_roam: bool = False,

    # 子树折叠和展开的交互,默认打开 。由于绘图区域是有限的,而通常一个树图的节点可能会比较多,
    # 这样就会出现节点之间相互遮盖的问题。为了避免这一问题,可以将暂时无关的子树折叠收起,
    # 等到需要时再将其展开。如上面径向布局树图示例,节点中心用蓝色填充的就是折叠收起的子树,可以点击将其展开。
    # 注意:如果配置自定义的图片作为节点的标记,是无法通过填充色来区分当前节点是否有折叠的子树的。
    # 而目前暂不支持,上传两张图片分别表示节点折叠和展开两种状态。所以,如果想明确地显示节点的两种状态,
    # 建议使用 ECharts 常规的标记类型,如 'emptyCircle' 等。
    is_expand_and_collapse: bool = True,

    # 树图初始展开的层级(深度)。根节点是第 0 层,然后是第 1 层、第 2 层,... ,
    # 直到叶子节点。该配置项主要和 折叠展开 交互一起使用,目的还是为了防止一次展示过多节点,
    # 节点之间发生遮盖。如果设置为 -1 或者 null 或者 undefined,所有节点都将展开。
    initial_tree_depth: Optional[Numeric] = None,

    # 标签配置项,参考 `series_options.LabelOpts`
    label_opts: Union[opts.LabelOpts, dict] = opts.LabelOpts(),

    # 叶子节点标签配置项,参考 `series_options.LabelOpts`
    leaves_label_opts: Union[opts.LabelOpts, dict] = opts.LabelOpts(),

    # 提示框组件配置项,参考 `series_options.TooltipOpts`
    tooltip_opts: Union[opts.TooltipOpts, dict, None] = None,
)

1.2 配置树图

我们将在一个Base版的树图代码的基础上一步一步配置树图。

Base

from pyecharts import options as opts
from pyecharts.charts import Tree


data = [
    {
        "children": [
            {"name": "B"},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]


c = (
    Tree()
    .add("", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版"))
)

c.render_notebook()

[图片上传失败...(image-5a05e5-1646121362033)]

初始化配置

Tree的构造函数可以接收一个初始化配置项,形参为init_opts,接收一个InitOpts。这个配置不懂的见上一篇教程。这里只显示配置后的结果。

class Tree(
    # 初始化配置项,参考 `global_options.InitOpts`
    init_opts: opts.InitOpts = opts.InitOpts()
)

配置背景、图纸大小:

from pyecharts import options as opts
from pyecharts.charts import Tree
from pyecharts.commons.utils import JsCode


data = [
    {
        "children": [
            {"name": "B"},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]
c = (
    Tree(init_opts=opts.InitOpts(width="600px",height="400px", bg_color={"type": "pattern", "image": JsCode("img"), "repeat": "no-repeat", "size":"100%"}))
    .add("", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版"))
    .add_js_funcs(
    """
    var img = new Image(); img.src = 'https://raw.githubusercontent.com/WinddyAkoky/awesome-gallery/main/20220301104818.png';
    """)
)

c.render_notebook()
image

配置标题颜色

from pyecharts import options as opts
from pyecharts.charts import Tree
from pyecharts.commons.utils import JsCode


data = [
    {
        "children": [
            {"name": "B"},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]
c = (
    Tree(init_opts=opts.InitOpts(width="600px",height="400px", bg_color={"type": "pattern", "image": JsCode("img"), "repeat": "no-repeat", "size":"100%"}))
    .add("", data)
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版",title_textstyle_opts={'color':"white"}))
    .add_js_funcs(
    """
    var img = new Image(); img.src = 'https://raw.githubusercontent.com/WinddyAkoky/awesome-gallery/main/20220301104818.png';
    """)
)
# 
c.render_notebook()
image

配置add函数

add函数的形参在上面已经贴出来了,读者可以根据自己的需要进行配置。这里我只配置其中几个形参。

from pyecharts import options as opts
from pyecharts.charts import Tree
from pyecharts.commons.utils import JsCode


data = [
    {
        "children": [
            {"name": "B"},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]
c = (
    Tree(init_opts=opts.InitOpts(width="600px",height="400px", bg_color={"type": "pattern", "image": JsCode("img"), "repeat": "no-repeat", "size":"100%"}))
    .add("", data=data, symbol="circle", symbol_size=[10,10], is_roam=True)
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版",title_textstyle_opts={'color':"white"}))
    .add_js_funcs(
    """
    var img = new Image(); img.src = 'https://raw.githubusercontent.com/WinddyAkoky/awesome-gallery/main/20220301104818.png';
    """)
)
# 
c.render_notebook()
image

调节标签颜色与大小

从上图看到,我们的背景选用星空的照片,这导致节点的标签不太清晰。因此我们想把它调成白色。

设置add函数中的label_opts

from pyecharts import options as opts
from pyecharts.charts import Tree
from pyecharts.commons.utils import JsCode


data = [
    {
        "children": [
            {"name": "B"},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]
c = (
    Tree(init_opts=opts.InitOpts(width="600px",height="400px", bg_color={"type": "pattern", "image": JsCode("img"), "repeat": "no-repeat", "size":"100%"}))
    .add("", data=data, symbol="circle", symbol_size=[10,10], is_roam=True, 
         label_opts=opts.LabelOpts(color='white', font_size=15))
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版",title_textstyle_opts={'color':"white"}))
    .add_js_funcs(
    """
    var img = new Image(); img.src = 'https://raw.githubusercontent.com/WinddyAkoky/awesome-gallery/main/20220301104818.png';
    """)
)
# 
c.render_notebook()
image

突出某个节点的颜色

比如说,我们希望强调节点B,并把节点B标记为红色。这该怎么做呢?

注意,要标记一个节点的颜色,这个节点的形状必须是实心的,如果节点的symble设置成空心(如emptyCircle),那么设置后的结果有可能会看不到。

data中的节点添加'itemStyle':{'color':"red"}即可。

from pyecharts import options as opts
from pyecharts.charts import Tree
from pyecharts.commons.utils import JsCode


data = [
    {
        "children": [
            {"name": "B", 'itemStyle':{'color':"red"}},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]
c = (
    Tree(init_opts=opts.InitOpts(width="600px",height="400px", bg_color={"type": "pattern", "image": JsCode("img"), "repeat": "no-repeat", "size":"100%"}))
    .add("", data=data, symbol="circle", symbol_size=[10,10], is_roam=True, 
         label_opts=opts.LabelOpts(color='white', font_size=15))
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版",title_textstyle_opts={'color':"white"}))
    .add_js_funcs(
    """
    var img = new Image(); img.src = 'https://raw.githubusercontent.com/WinddyAkoky/awesome-gallery/main/20220301104818.png';
    """)
)
# 
c.render_notebook()
image

强调某个连接

我们不仅可以标记出节点B的颜色,还可以标记出与之相连的连接。

data中的节点添加'itemStyle':{'color':"red"}即可。

from pyecharts import options as opts
from pyecharts.charts import Tree
from pyecharts.commons.utils import JsCode


data = [
    {
        "children": [
            {"name": "B", 'itemStyle':{'color':"red"}, "lineStyle":{'color':'red', 'width':3}},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]
c = (
    Tree(init_opts=opts.InitOpts(width="600px",height="400px", bg_color={"type": "pattern", "image": JsCode("img"), "repeat": "no-repeat", "size":"100%"}))
    .add("", data=data, symbol="circle", symbol_size=[10,10], is_roam=True, 
         label_opts=opts.LabelOpts(color='white', font_size=15))
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版",title_textstyle_opts={'color':"white"}))
    .add_js_funcs(
    """
    var img = new Image(); img.src = 'https://raw.githubusercontent.com/WinddyAkoky/awesome-gallery/main/20220301104818.png';
    """)
)
# 
c.render_notebook()

[图片上传失败...(image-4aa8ec-1646121362033)]

突出某个节点标签的颜色

from pyecharts import options as opts
from pyecharts.charts import Tree
from pyecharts.commons.utils import JsCode


data = [
    {
        "children": [
            {"name": "B", 'itemStyle':{'color':"red"}, "lineStyle":{'color':'red', 'width':3}, "label":{"color":'red'}},
            {
                "children": [{"children": [{"name": "I"}], "name": "E"}, {"name": "F"}],
                "name": "C",
            },
            {
                "children": [
                    {"children": [{"name": "J"}, {"name": "K"}], "name": "G"},
                    {"name": "H"},
                ],
                "name": "D",
            },
        ],
        "name": "A",
    }
]
c = (
    Tree(init_opts=opts.InitOpts(width="600px",height="400px", bg_color={"type": "pattern", "image": JsCode("img"), "repeat": "no-repeat", "size":"100%"}))
    .add("", data=data, symbol="circle", symbol_size=[10,10], is_roam=True, 
         label_opts=opts.LabelOpts(color='white', font_size=15))
    .set_global_opts(title_opts=opts.TitleOpts(title="Tree-Base版",title_textstyle_opts={'color':"white"}))
    .add_js_funcs(
    """
    var img = new Image(); img.src = 'https://raw.githubusercontent.com/WinddyAkoky/awesome-gallery/main/20220301104818.png';
    """)
)
# 
c.render_notebook()
image

2. 矩阵树形

矩阵树形类TreeMap:

class TreeMap(
    # 初始化配置项,参考 `global_options.InitOpts`
    init_opts: opts.InitOpts = opts.InitOpts()
)

该函数也有一个add函数用于添加数据:

def add(
    # 系列名称,用于 tooltip 的显示,legend 的图例筛选。
    series_name: str,

    # 系列数据项
    data: Sequence[Union[opts.TreeItem, dict]],

    # 是否选中图例。
    is_selected: bool = True,

    # leaf_depth 表示『展示几层』,层次更深的节点则被隐藏起来。
    # 设置了 leafDepth 后,下钻(drill down)功能开启。drill down 功能即点击后才展示子层级。
    # 例如,leafDepth 设置为 1,表示展示一层节点。
    leaf_depth: Optional[Numeric] = None,

    # treemap 组件离容器左侧的距离。
    # left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,
    # 也可以是 'left', 'center', 'right'。
    # 如果 left 的值为'left', 'center', 'right',组件会根据相应的位置自动对齐。
    pos_left: Optional[str] = None,

    # treemap 组件离容器右侧的距离。
    # right 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    pos_right: Optional[str] = None,

    # treemap 组件离容器上侧的距离。
    # top 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,
    # 也可以是 'top', 'middle', 'bottom'。
    # 如果 top 的值为'top', 'middle', 'bottom',组件会根据相应的位置自动对齐。
    pos_top: Optional[str] = None,

    # treemap 组件离容器下侧的距离。
    # bottom 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    pos_bottom: Optional[str] = None,

    # treemap 组件的宽度。
    width: types.Union[str, types.Numeric] = "80%",

    # treemap 组件的高度。
    height: types.Union[str, types.Numeric] = "80%",

    # 期望矩形长宽比率。布局计算时会尽量向这个比率靠近。
    # 默认为黄金比:0.5 * (1 + Math.sqrt(5))。
    square_ratio: types.Optional[types.JSFunc] = None,

    # 当节点可以下钻时的提示符。只能是字符。
    drilldown_icon: str = "▶",

    # 是否开启拖拽漫游(移动和缩放)。可取值有:
    # false:关闭。
    # 'scale' 或 'zoom':只能够缩放。
    # 'move' 或 'pan':只能够平移。
    # true:缩放和平移均可。
    roam: types.Union[bool, str] = True,

    # 点击节点后的行为。可取值为
    # false:节点点击无反应。
    # 'zoomToNode':点击节点后缩放到节点。
    # 'link':如果节点数据中有 link 点击节点后会进行超链接跳转。
    node_click: types.Union[bool, str] = "zoomToNode",

    # 点击某个节点,会自动放大那个节点到合适的比例(节点占可视区域的面积比例),这个配置项就是这个比例。
    zoom_to_node_ratio: types.Numeric = 0.32 * 0.32,

    # treemap 中采用『三级配置』:
    #『每个节点』->『每个层级』->『每个系列』。
    # 即我们可以对每个节点进行配置,也可以对树的每个层级进行配置,也可以 series 上设置全局配置。节点上的设置,优先级最高。
    # 最常用的是『每个层级进行配置』,levels 配置项就是每个层级的配置
    levels: types.TreeMapLevel = None,

    # 当前层级的最小 value 值。如果不设置则自动统计。
    visual_min: Optional[Numeric] = None,

    # 当前层级的最大 value 值。如果不设置则自动统计。
    visual_max: Optional[Numeric] = None,

    # 本系列默认的 颜色透明度 选取范围。数值范围 0 ~ 1。
    color_alpha: types.Union[types.Numeric, types.Sequence] = None,

    # 本系列默认的 颜色饱和度 选取范围。数值范围 0 ~ 1。
    color_saturation: types.Union[types.Numeric, types.Sequence] = None,

    # 表示同一层级节点,在颜色列表中(参见 color 属性)选择时,按照什么来选择。可选值:
    # 'value' 将节点的值(即 series-treemap.data.value)映射到颜色列表中。这样得到的颜色,反应了节点值的大小。
    # 'index' 将节点的 index(序号)映射到颜色列表中。即同一层级中,第一个节点取颜色列表中第一个颜色,第二个节点取第二个。
    # 这样得到的颜色,便于区分相邻节点。
    # 'id' 将节点的 id 映射到颜色列表中。
    # id 是用户指定的,这样能够使得,在 treemap 通过 setOption 变化数值时,同一 id 映射到同一颜色,保持一致性。
    color_mapping_by: str = "index",

    # 如果某个节点的矩形的面积,小于这个数值(单位:px平方),这个节点就不显示。
    # 如果不加这个限制,很小的节点会影响显示效果。
    # 关于视觉设置,详见 series-treemap.levels。
    visible_min: types.Numeric = 10,

    # 如果某个节点的矩形面积,小于这个数值(单位:px平方),则不显示这个节点的子节点。
    # 这能够在矩形面积不足够大时候,隐藏节点的细节。当用户用鼠标缩放节点时,如果面积大于此阈值,又会显示子节点。
    # 关于视觉设置,详见 series-treemap.levels。
    children_visible_min: types.Optional[types.Numeric] = None,

    # 标签配置项,参考 `series_options.LabelOpts`
    label_opts: Union[opts.LabelOpts, dict] = opts.LabelOpts(position="inside"),

    # 父级标签配置项,参考 `series_options.LabelOpts`
    upper_label_opts: types.Label = opts.LabelOpts(position="inside"),

    # 提示框组件配置项,参考 `series_options.TooltipOpts`
    tooltip_opts: Union[opts.TooltipOpts, dict, None] = None,

    # 图形样式配置,参考 `global_options.ItemStyleOpts`
    itemstyle_opts: types.ItemStyle = None,

    # 面包屑控件配置,参考 `TreeMapBreadcrumbOpts`
    breadcrumb_opts: types.TreeMapBreadcrumb = None,
)

面包屑控制类TreeMapBreadcrumbOpts

class TreeMapBreadcrumbOpts(
    # 是否显示面包屑。
    is_show: bool = True,

    # 组件离容器左侧的距离。
    # left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,也可以是 'left', 'center', 'right'。
    # 如果 left 的值为'left', 'center', 'right',组件会根据相应的位置自动对齐。
    pos_left: Union[str, Numeric] = "center",

    # 组件离容器右侧的距离。
    # right 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    # 默认自适应。
    pos_right: Union[str, Numeric] = "auto",

    # 组件离容器上侧的距离。
    # top 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,也可以是 'top', 'middle', 'bottom'。
    # 如果 top 的值为'top', 'middle', 'bottom',组件会根据相应的位置自动对齐。
    pos_top: Union[str, Numeric] = "auto",

    # 组件离容器下侧的距离。
    # bottom 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
    # 默认自适应。
    pos_bottom: Union[str, Numeric] = 0,

    # 面包屑的高度。
    height: Numeric = 22,

    # 当面包屑没有内容时候,设个最小宽度。
    empty_item_width: Numeric = 25,

    # 图形样式。参考 `global_options.ItemStyleOpts`
    item_opts: ItemStyleOpts = ItemStyleOpts(),
)

图形样式类TreeMapItemStyleOpts

class TreeMapItemStyleOpts(
    # 矩形的颜色。
    color: Optional[str] = None,

    # 矩形颜色的透明度。取值范围是 0 ~ 1 之间的浮点数。
    color_alpha: Union[Numeric, Sequence] = None,

    # 矩形颜色的饱和度。取值范围是 0 ~ 1 之间的浮点数。
    color_saturation: Union[Numeric, Sequence] = None,

    # 矩形边框 和 矩形间隔(gap)的颜色。
    border_color: Optional[str] = None,

    # 矩形边框线宽。为 0 时无边框。而矩形的内部子矩形(子节点)的间隔距离是由 gapWidth 指定的。
    border_width: Numeric = 0,

    # 矩形边框的颜色的饱和度。取值范围是 0 ~ 1 之间的浮点数。
    border_color_saturation: Union[Numeric, Sequence] = None,

    # 矩形内部子矩形(子节点)的间隔距离。
    gap_width: Numeric = 0,

    # 每个矩形的描边颜色。
    stroke_color: Optional[str] = None,

    # 每个矩形的描边宽度。
    stroke_width: Optional[Numeric] = None,
)

层级配置类TreeMapLevelsOpts

class TreeMapLevelsOpts(
    # 矩形颜色的透明度。取值范围是 0 ~ 1 之间的浮点数。
    color_alpha: Union[Numeric, Sequence] = None,

    # 矩形颜色的饱和度。取值范围是 0 ~ 1 之间的浮点数。
    color_saturation: Union[Numeric, Sequence] = None,

    # 表示同一层级节点,在颜色列表中(参见 color 属性)选择时,按照什么来选择。可选值:
    # 'value' 将节点的值(即 series-treemap.data.value)映射到颜色列表中。这样得到的颜色,反应了节点值的大小。
    # 'index' 将节点的 index(序号)映射到颜色列表中。即同一层级中,第一个节点取颜色列表中第一个颜色,第二个节点取第二个。
    # 这样得到的颜色,便于区分相邻节点。
    # 'id' 将节点的 id 映射到颜色列表中。
    # id 是用户指定的,这样能够使得,在 treemap 通过 setOption 变化数值时,同一 id 映射到同一颜色,保持一致性。
    color_mapping_by: str = "index",

    # 矩形树图的 Item 配置,参考 `class pyecharts.options.TreeMapItemStyleOpts`
    treemap_itemstyle_opts: Union[TreeMapItemStyleOpts, dict, None] = None,

    # 每个矩形中,文本标签的样式,参考 `series_options.LabelOpts`
    label_opts: Union[LabelOpts, dict, None] = None,

    # 用于显示矩形的父节点的标签。参考 `series_options.LabelOpts`
    upper_label_opts: Union[LabelOpts, dict, None] = None,
)

2.1 快速上手

import json

from pyecharts import options as opts
from pyecharts.charts import TreeMap


data = [
    {"value": 40, "name": "我是A"},
    {
        "value": 180,
        "name": "我是B",
        "children": [
            {
                "value": 76,
                "name": "我是B.children",
                "children": [
                    {"value": 12, "name": "我是B.children.a"},
                    {"value": 28, "name": "我是B.children.b"},
                    {"value": 20, "name": "我是B.children.c"},
                    {"value": 16, 
                     "name": "我是B.children.d",
                    "children": [
                        {"value":6, "name": "B-c-a"},
                        {"value":6, "name": "B-c-b"}
                    ]},
                ],
            }
        ],
    },
]

c = (
    TreeMap()
    .add(
        series_name="演示数据",
        data=data
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="TreeMap配置"))
)

c.render_notebook()
image

2.1 配置矩阵树图

太简单的字段就不多废话了,讲一个比较特殊的形参。

配置层级样式

上图中已经展示了初步的矩阵树形图,但是块与块之间连在一起,没有间隔,不太好看。为此我们需要去配置level这个形参来调节矩阵边框的大小与间隔。

import json

from pyecharts import options as opts
from pyecharts.charts import TreeMap


data = [
    {"value": 40, "name": "我是A"},
    {
        "value": 180,
        "name": "我是B",
        "children": [
            {
                "value": 76,
                "name": "我是B.children",
                "children": [
                    {"value": 12, "name": "我是B.children.a"},
                    {"value": 28, "name": "我是B.children.b"},
                    {"value": 20, "name": "我是B.children.c"},
                    {"value": 12, 
                     "name": "我是B.children.d",
                    "children": [
                        {"value":6, "name": "B-c-a"},
                        {"value":6, "name": "B-c-b"}
                    ]},
                ],
            },
            {"value": 14, "name":"B-d"},
        ],
    },
]

c = (
    TreeMap()
    .add(
        series_name="演示数据",
        data=data,
        levels=[
            opts.TreeMapLevelsOpts(
                treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                    border_color="#555", border_width=10, gap_width=40
                )
            ),
        ],
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="TreeMap配置"))
)

c.render_notebook()
image

我们往level参数中传入了一个TreeMapLevelsOpts,并控制border_color="#555", border_width=10, gap_width=40(边框的颜色,边框的宽度和块之间的间隔)。但是,可以发现,这个设置仅在第一层树上发挥了作用。从第二层开始就不发生作用了。若想在树的第二层也有类似的作用,需要在添加一个TreeMapLevelsOpts,即:

import json

from pyecharts import options as opts
from pyecharts.charts import TreeMap


data = [
    {"value": 40, "name": "我是A"},
    {
        "value": 180,
        "name": "我是B",
        "children": [
            {
                "value": 76,
                "name": "我是B.children",
                "children": [
                    {"value": 12, "name": "我是B.children.a"},
                    {"value": 28, "name": "我是B.children.b"},
                    {"value": 20, "name": "我是B.children.c"},
                    {"value": 12, 
                     "name": "我是B.children.d",
                    "children": [
                        {"value":6, "name": "B-c-a"},
                        {"value":6, "name": "B-c-b"}
                    ]},
                ],
            },
            {"value": 14, "name":"B-d"},
        ],
    },
]

c = (
    TreeMap()
    .add(
        series_name="演示数据",
        data=data,
        levels=[
            opts.TreeMapLevelsOpts(
                treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                    border_color="#555", border_width=10, gap_width=40
                )
            ),
            opts.TreeMapLevelsOpts(
                color_saturation=[0.3, 0.6],
                treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                    border_color_saturation=0.7, gap_width=10, border_width=6
                ),
            )
        ],
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="TreeMap配置"))
)

c.render_notebook()
image

从上图可以看到树的第二层也有边框与间隔了。依此类推,想配置更精美的矩阵树图,多配置几个TreeMapLevelsOpts即可。下面是最终调节后的结果:

import json

from pyecharts import options as opts
from pyecharts.charts import TreeMap


data = [
    {"value": 40, "name": "我是A"},
    {
        "value": 180,
        "name": "我是B",
        "children": [
            {
                "value": 76,
                "name": "我是B.children",
                "children": [
                    {"value": 12, "name": "我是B.children.a"},
                    {"value": 28, "name": "我是B.children.b"},
                    {"value": 20, "name": "我是B.children.c"},
                    {"value": 12, 
                     "name": "我是B.children.d",
                    "children": [
                        {"value":6, "name": "B-c-a"},
                        {"value":6, "name": "B-c-b"}
                    ]},
                ],
            },
            {"value": 14, "name":"B-d"},
        ],
    },
]

c = (
    TreeMap()
    .add(
        series_name="演示数据",
        data=data,
        levels=[
            opts.TreeMapLevelsOpts(
                treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                    border_color="#555", border_width=4, gap_width=4
                )
            ),
            opts.TreeMapLevelsOpts(
                color_saturation=[0.3, 0.6],
                treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                    border_color_saturation=0.7, gap_width=2, border_width=2
                ),
            ),
            opts.TreeMapLevelsOpts(
                color_saturation=[0.3, 0.5],
                treemap_itemstyle_opts=opts.TreeMapItemStyleOpts(
                    border_color_saturation=0.6, gap_width=1
                ),
            ),
            opts.TreeMapLevelsOpts(color_saturation=[0.3, 0.5]),
        ],
    )
    .set_global_opts(title_opts=opts.TitleOpts(title="TreeMap配置"))
)

c.render_notebook()
image
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,200评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,526评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,321评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,601评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,446评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,345评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,753评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,405评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,712评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,743评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,529评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,369评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,770评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,026评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,301评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,732评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,927评论 2 336

推荐阅读更多精彩内容