有没有办法防止 plotly 上的图例在水平方向时向上移动到图表中?

Is there a way to prevent the legend on plotly from moving up into the chart when its orientation is horizontal?

上下文

我目前正在创建数据可视化 Web 应用程序。我正在使用 Plotly 创建时间序列。我在使用图例时遇到问题。

我希望图例保留在底部,因为数据标签很长,因此会干扰数据的整体维度。我选择的方向是 horizontal.

但是当我添加更多数据时,图例会向上移动而不是保持在固定位置,以便可以向下添加新数据。相反,随着新数据添加到图表中,整个图例会上升。

我的代码如下:

plotly_fig = px.line(data_frame=dataframe_cols1,x=dataframe_cols1.index,y=Columns_select1,
                            width=780, height=730) # Get data from the dataframe with selected columns, choose the x axis as the index of the dataframe, y axis is the data that will be multiselected
        
        # Legend settings
        plotly_fig.update_layout(showlegend=True)       
        plotly_fig.update_layout(legend=dict(
                          orientation = "h",
                          yanchor="bottom",
                          y=-.50,
                          xanchor="right",
                          x=1
                        ))    

问题

如何防止图例在添加新数据时向上移动?换句话说,我怎样才能将图例固定在其位置以防止它 'mingling' 与图表一起出现?

真的只有一种方法; 腾出空间并调整图例位置

在这种情况下,您可以通过以下方式做到这一点:

  1. fig.update_layout(height=1000)
  2. fig.update_layout(margin=dict(l=20, r=20, t=20, b=20)
  3. fig.update_layout(legend=dict(orientation = "h", yanchor="bottom",y=-1.1,xanchor="left", x=0))

样本图

完整代码:

import pandas as pd
import numpy as np
import plotly
import plotly.express as px

# data
start = 2021
ncols = 20
nrows = 1000
cols = [str(i) for i in np.arange(start, start+ncols)]
df = pd.DataFrame(np.random.randint(-1,2, (nrows,ncols)), columns = cols).cumsum()
df.iloc[0] = 0

# figure
fig = px.line(df, x=df.index, y=cols,width=780, height=730)

# updating names
fig.for_each_trace(lambda t: t.update(name=t.name + ' Very lengthy name to reproduce the challenge') )
    
# legend position
fig.update_layout(showlegend=True) 
fig.update_layout(legend=dict(
                  orientation = "h",
                  yanchor="bottom",
                  y=-1.1,
                  xanchor="left",
                  x=0)) 

height = 1000
fig.update_layout(
    autosize=False,
    width=750,
    height=height)

fig.update_layout(
    margin=dict(l=20, r=20, t=20, b=20),
    paper_bgcolor="LightSteelBlue")

# plotly.offline.plot(fig, filename='C:/plotlyplots/lifeExp.html')
fig.show()