如何给 plotly treemap 加上百分比数字
可视是感觉,数字是科学
背景
如果想用 Python 绘制带有层级关系的面积比例拼图,plotly 的 treemap 是最便捷的方式,只需对数据格式稍作调整,即可一行代码出图:
import plotly.express as px
# 方式1 通过指定names和parent
px.treemap(names=["a","b","c","d","e"], parents=["x","a","b","b","c"])
# 方式2 通过path参数传入层级列表
px.treemap(df, path=[px.Constant("All"), "type"], values="count")
但默认出图时,生成的 treemap 仅在每块区域左上角显示区域名字,缺少数字展示,如何补充数值或百分比展示呢?
方案
对于 plotly 而言,每幅图(Figure)由一系列的路径组成(即 trace,treemap 即为其中一种 trace),而每个路径trace有其文本显示参数textinfo,不同的trace其textinfo可取值不同,如 treemap 的可取值:
Any combination of"label","text","value","current path","percent root","percent entry","percent parent"joined with a"+"OR"none".
因此,可以指定textinfo 包含 "percent parent" 来显示当前板块在父级板块中的占比:
fig = px.treemap(df, path=[px.Constant("All"), "type"], values="count")
fig.update_traces(textinfo="label+percent parent")
fig.show()
同理,"percent root"及"percent entry"指当前板块在根节点及全体中的占比。