在 plotly 中使用 graph_objects 类的树形图
Plotly 是一个Python库,用于设计图形,尤其是交互式图形。它可以绘制各种图形和图表,如直方图、条形图、箱线图、散布图等等。它主要用于数据分析和财务分析。 plotly 是一个交互式可视化库。
使用 graph_objects 类的树形图
Treemapping 是一种数据可视化程序,可用于使用封闭的矩形展示分级数据。数据通过使用矩形、尺寸和绘图颜色表示为分支和子分支。树形图有助于明显区分数据值之间的类别。
Syntax: class plotly.graph_objects.Treemap(arg=None, branchvalues=None, count=None, customdata=None, hoverinfo=None, **kwargs)
Parameters:
arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Treemap
branchvalues: Determines how the items in values are summed.
count: Determines default for values when it is not provided, by inferring a 1 for each of the “leaves” and/or “branches”, otherwise 0.
customdata: Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, “scatter” traces also appends customdata items in the markers DOM elements
hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired.
例子:
Python3
import plotly.graph_objects as go
fig = go.Figure(go.Treemap(
labels = ["A", "B", "C", "D", "E"],
parents = ["", "A", "B", "C", "A"]
))
fig.show()
Python3
import plotly.graph_objects as go
fig = go.Figure(go.Treemap(
labels = ["A", "B", "C", "D", "E"],
parents = ["", "A", "B", "C", "A"],
marker_colors = ["blue", "pink", "red",
"royalblue", "lightgray", ]
))
fig.show()
Python3
import plotly.graph_objects as go
fig = go.Figure(go.Treemap(
labels = ["A", "B", "C", "D", "E"],
parents = ["", "A", "B", "C", "A"],
marker_colors = ["blue", "pink"]
))
fig.update_layout(uniformtext = dict(minsize = 15,
mode ='hide'))
fig.show()
输出:
设置树形图扇区的颜色
要更改树形图中的颜色扇区,有三种不同的方法:
- 标记.颜色
- 配色
- 色阶
例子:
Python3
import plotly.graph_objects as go
fig = go.Figure(go.Treemap(
labels = ["A", "B", "C", "D", "E"],
parents = ["", "A", "B", "C", "A"],
marker_colors = ["blue", "pink", "red",
"royalblue", "lightgray", ]
))
fig.show()
输出:
更改文本字体大小
在 plotly 中,标签可以通过使用 uniformtext 布局参数保持相同的大小。字体大小由 minsize 属性设置,模式属性设置为标签无法与所需的字体大小匹配:要么隐藏它们,要么用溢出显示它们。
Python3
import plotly.graph_objects as go
fig = go.Figure(go.Treemap(
labels = ["A", "B", "C", "D", "E"],
parents = ["", "A", "B", "C", "A"],
marker_colors = ["blue", "pink"]
))
fig.update_layout(uniformtext = dict(minsize = 15,
mode ='hide'))
fig.show()
输出: