graphviz官網對於xlabel的說明:
xlabel
External label for a node or edge
type: lblString, default: ""
- For nodes, the label will be placed outside of the node but near it.
- For edges, the label will be placed near the center of the edge. This can be useful in dot to avoid the occasional problem when the use of edge labels distorts the layout.
- For other layouts, the xlabel attribute can be viewed as a synonym for the
label
attribute.
These labels are added after all nodes and edges have been placed.
The labels will be placed so that they do not overlap any node or label. This means it may not be possible to place all of them. To force placing all of them, set forcelabels=true
.
xlabel
外部標簽,適用於節點或邊
類型:lblString,默認值:””。
對於節點,標簽將被放置在節點的外側但接近節點。
對於邊,標簽將被放置在邊的中心附近。這在 dot 布局中非常有用,可以避免邊的標簽使用導致布局扭曲的偶發問題。
對於其他布局,xlabel 屬性可以被視為 label 屬性的同義詞。
這些標簽在所有節點和邊放置完畢後添加。
標簽將被放置在不與任何節點或標簽重疊的位置。這意味著可能無法放置所有標簽。要強制放置所有標簽,可以設置 forcelabels=true。
code(在node中使用xlabel參數):
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 13 19:56:57 2024
@author: SavingKing
"""
from graphviz import Digraph
dot = Digraph(comment='Kitting and Assembly Process', graph_attr={'rankdir': 'LR'})
# 添加節點
dot.node('Kitting', 'Kitting',xlabel='MVS\n(Material\nVerification\nStation)')
dot.node('Assembly', 'System Assembly')
dot.node('FirstInsp', 'First Insp.',xlabel="1st Cosmetic check")
dot.node('PreTest', 'Pre-Test')
# 添加邊
dot.edge('Kitting', 'Assembly')
dot.edge('Assembly', 'FirstInsp')
dot.edge('FirstInsp', 'PreTest')
# 渲染並查看圖形
dot.render('kitting_assembly_graph_lr', format='png', cleanup=True, view=True)
輸出的圖形
(xlabel自動放置於node的左下方,
無法調整):
解決方式,
設定子圖(name必須以cluster開頭)中
只有一個node
用子圖的label取代node的xlabel
並將子圖的外框設定為透明
code:
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 13 19:46:04 2024
@author: SavingKing
"""
from graphviz import Digraph
dot = Digraph(comment='Kitting and Assembly Process', graph_attr={'rankdir': 'LR'})
# 創建一個子圖,名為 'cluster_MVS' 注意需要用cluster開頭
with dot.subgraph(name='cluster_MVS') as c:
c.attr(label='MVS\n(Material\nVerification\nStation)')
c.attr(color='transparent') # 设置子图边框颜色为透明
c.node('Kitting', 'Kitting')
# 添加其他節點
dot.node('Assembly', 'System Assembly')
#dot.node('FirstInsp', 'First Insp.')
dot.node('PreTest', 'Pre-Test')
# 創建一個子圖,名為 'cluster_1st' #注意需要用cluster開頭
with dot.subgraph(name='cluster_1st') as c:
c.attr(label="1st Cosmetic check")
c.attr(color='transparent') # 设置子图边框颜色为透明
c.node('FirstInsp', 'First Insp.')
# 添加其他边
dot.edge('Kitting', 'Assembly')
dot.edge('Assembly', 'FirstInsp')
dot.edge('FirstInsp', 'PreTest')
# 渲染并查看图形
dot.render('kitting_assembly_graph_lr', format='png', cleanup=True, view=True)
生成的圖形(label放置在node的正上方):
雖然也無法控制位置,
不過label在node的正上方
比在左下方
看起來正常
推薦hahow線上學習python: https://igrape.net/30afN
近期留言