Plotly多行图例标志垂直对齐

huangapple go评论71阅读模式
英文:

Plotly multiline legend bullets vertical alignment

问题

Consider the following MWE:

import plotly.graph_objects as go

fig = go.Figure()
for i in range(4):
    fig.add_trace(
        go.Scatter(
            x=[1, 2, 3],
            y=[i]*3,
            name='在多行中分隔的非常长的图例'
        )
    )
fig.write_html('deleteme.html')

which produces this:
Plotly多行图例标志垂直对齐

Is it possible to change the alignment of the bullets in the legend to produce this instead? (I made it with Paint)
Plotly多行图例标志垂直对齐

In the previous trivial example this looks like a whim, however in more complex cases the alignment of the legend bullets makes it really confusing to know which is which:
Plotly多行图例标志垂直对齐

英文:

Consider the following MWE:

import plotly.graph_objects as go

fig = go.Figure()
for i in range(4):
	fig.add_trace(
		go.Scatter(
			x = [1,2,3],
			y = [i]*3,
			name = 'A very long legend<br>which I break in<br>multiple lines'
		)
	)
fig.write_html('deleteme.html')

which produces this:
Plotly多行图例标志垂直对齐

Is it possible to change the alignment of the bullets in the legend to produce this instead? (I made it with Paint)
Plotly多行图例标志垂直对齐

In the previous trivial example this looks like a whim, however in more complex cases the alignment of the legend bullets makes it really confusing to know which is which:
Plotly多行图例标志垂直对齐

答案1

得分: 2

@ user171780 感谢邀请。

您可以使用legend_valign来调整图例的位置,使用以下代码:fig.update_layout(legend_valign='top')

此外,您还可以在绘图时添加组,并使用legend_tracegroupgap定义图例之间的距离。

import plotly.graph_objects as go

fig = go.Figure()
for i in range(4):
    fig.add_trace(
        go.Scatter(
            x = [1,2,3],
            y = [i]*3,
            name = '一个非常长的图例<br>我分为<br>多行的例子',
            legendgroup = 'group' + str(i)
        )
    )

fig.update_layout(legend_valign='top')

fig.update_layout(legend_tracegroupgap=30)

fig.show()
英文:

@ user171780 Thanks for inviting.

You can adjust the position of the legend with legend_valign, with the code fig.update_layout(legend_valign='top').

Furthermore, you can adjust the distance between the legend with adding group during plotting and define the distance with legend_tracegroupgap.

import plotly.graph_objects as go

fig = go.Figure()
for i in range(4):
    fig.add_trace(
        go.Scatter(
            x = [1,2,3],
            y = [i]*3,
            name = 'A very long legend<br>which I break in<br>multiple lines',
            legendgroup = 'group' + str(i)
        )
    
    )
    
fig.update_layout(legend_valign='top')

fig.update_layout(legend_tracegroupgap=30)

fig.show()

huangapple
  • 本文由 发表于 2023年4月13日 17:16:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定