首页 > 解决方案 > Plotly:如何调整滑块和更新菜单的位置以为 x 轴刻度线腾出空间?

问题描述

我在我的 plotly express 图中使用了一个动画帧,但它与我的 x 轴重叠。我能做些什么 ?

这是我的代码:

data = pd.read_csv('file.csv')
fig = px.scatter(data, x = "model", y = "price", color="competitor", hover_data=['Discount'], animation_frame="date")
       

这是我的问题:如何降低动画帧栏?或者也许把它放在图表的顶部?或者将 x 轴移动到图形顶部而不是底部?

在此处输入图像描述

标签: pythonpython-3.xplotly

解决方案


您可以通过调整填充轻松调整绘图本身的边距,以及滑块和相应更新按钮的位置:

fig.update_layout(margin=dict(l=20, r=20, t=20, b=200),paper_bgcolor="LightSteelBlue")
fig['layout']['updatemenus'][0]['pad']=dict(r= 10, t= 150)
fig['layout']['sliders'][0]['pad']=dict(r= 10, t= 150,)

上面的代码片段会变成这样:

在此处输入图像描述

...进入这个:

在此处输入图像描述

完整代码:

import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])

fig.update_layout(margin=dict(l=20, r=20, t=20, b=200),paper_bgcolor="LightSteelBlue")
fig['layout']['updatemenus'][0]['pad']=dict(r= 10, t= 150)
fig['layout']['sliders'][0]['pad']=dict(r= 10, t= 150,)
fig.show()

推荐阅读