[英]plotly sankey diagram positioning
我想給 Plotly Sankey 圖添加一些注釋。
我想將它們直接繪制在 sankey 節點塊上(具有相同的 x 位置),但找不到方法,甚至找不到節點的 X 坐標。 (認為獲取它們而不是手動添加會更好,因為 sankey 級別的數量可能會改變)
如果我們采用這個基本示例,我想在相應節點上添加“A”、“B”和“C”標簽
import plotly.graph_objects as go
fig = go.Figure(data=[go.Sankey(
node = dict(
pad = 15,
thickness = 20,
line = dict(color = "black", width = 0.5),
label = ["A1", "A2", "B1", "B2", "C1", "C2"],
color = "blue"
),
link = dict(
source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
target = [2, 3, 3, 4, 4, 5],
value = [8, 4, 2, 8, 4, 2]
))])
fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()
這是對先前答案的不必要擴展。
如果我們從基本圖開始:
import plotly.graph_objects as go
fig = go.Figure(data=[go.Sankey(
node = dict(
pad = 15,
thickness = 20,
line = dict(color = "black", width = 0.5),
label = ["A1", "A2", "B1", "B2", "C1", "C2"],
color = "blue"
),
link = dict(
source = [0, 1, 0, 2, 3, 3], # indices correspond to labels, eg A1, A2, A1, B1, ...
target = [2, 3, 3, 4, 4, 5],
value = [8, 4, 2, 8, 4, 2]
))])
fig.write_image("fig1.png")
fig.show()
然后添加注釋。 如果我們不指定位置,它將位於 plot 的中間。
fig.add_annotation(text='<b>DEFAULT</b>',font_color="red") # unspecified position
我們可以使用 x,y 坐標指定位置:
fig.add_annotation(x=0, y=0, text='<b>(0,0)</b>', font_color="red")
fig.add_annotation(x=1, y=1, text='<b>(1,1)</b>', font_color="red")
現在我們知道了布局,我們可以將所需的標簽放入列表中,並自動將其用於 position,如下所示:
lab_list = ['<b>A</b>','<b>B</b>','<b>C</b>']
for i, text in enumerate(lab_list):
x_val = i / (len(lab_list)-1)
fig.add_annotation(
x=x_val,
y=1.06,
text=text,
showarrow=False
)
在這種情況下,您可以使用fig.add_annotation()
。 在fig.update_layout()
行下面添加以下幾行
fig.add_annotation(dict(font=dict(color="black",size=12), x=0, y=1.06, showarrow=False, text='<b>A</b>'))
fig.add_annotation(dict(font=dict(color="black",size=12), x=0.5, y=1.06, showarrow=False, text='<b>B</b>'))
fig.add_annotation(dict(font=dict(color="black",size=12), x=1, y=1.06, showarrow=False, text='<b>C</b>'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.