Des*_*ond 2 python data-visualization plotly plotly-python
语境
我目前正在创建一个数据可视化网络应用程序。我正在使用 Plotly 创建时间序列。我对传说有疑问。
我希望图例保留在底部,因为数据的标签很长,因此会干扰数据的整体尺寸。我选择的方向是水平的。
但当我添加更多数据时,图例会向上移动而不是保持在固定位置,以便可以向下添加新数据。相反,随着新数据添加到图表中,整个图例都会上升。
我的代码如下:
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
))
Run Code Online (Sandbox Code Playgroud)
问题
添加新数据时如何防止图例向上移动?换句话说,如何将图例固定在其位置以防止其与图表“混合”?
实际上只有一种方法;腾出空间并调整图例位置。
在这种情况下,您可以通过以下方式做到这一点:
fig.update_layout(height=1000)fig.update_layout(margin=dict(l=20, r=20, t=20, b=20)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()
Run Code Online (Sandbox Code Playgroud)