如何为Python Plotly散点图的长标题添加水平滚动条
解决Plotly散点图长标题添加水平滚动条的问题
Plotly原生标题组件不支持直接添加滚动条,我们可以通过在标题中嵌入带样式的HTML <div> 来实现需求,同时调整图表边距避免标题与图表区域重叠。
修改步骤:
- 用HTML
<div>包裹长标题,设置水平滚动、不换行和匹配图表可用宽度的样式 - 增大图表顶部边距,为滚动标题预留足够空间
- 调整标题内边距,避免布局错位
修改后的代码:
def show_products(products: list[ProductInfo], title: str) -> None: # 增大顶部边距,为滚动标题留出空间 layout = go.Layout( autosize=False, width=1500, height=1500, xaxis=go.layout.XAxis(linecolor="black", linewidth=5, mirror=True), yaxis=go.layout.YAxis(linecolor="black", linewidth=5, mirror=True), margin=go.layout.Margin(l=50, r=50, b=100, t=120, pad=4), # 调整顶部边距值 ) fig = go.Figure(layout=layout) for product in products: add_scatter_plot( fig, product, name_format="%website - %name - %id", ) # 用带滚动样式的HTML div包裹标题文本 title_html = f'<div style="width: 1400px; overflow-x: auto; white-space: nowrap; font-size: 12px; color: #000000;">{title}</div>' title_ = dict( text=title_html, x=0.5, y=.97, xanchor='center', yanchor='top', pad=dict(t=0), # 移除负内边距,避免标题上移 font=dict( size=12, color='#000000' ) ) config_figure(fig, title_)
关键细节说明:
width: 1400px:图表总宽度1500px,减去左右边距各50px,确保div宽度匹配图表可用区域overflow-x: auto:当标题超出div宽度时自动显示水平滚动条white-space: nowrap:强制标题文本不换行,保证滚动效果margin.t=120:增大顶部边距,避免滚动标题与图表内容重叠,可根据实际标题高度微调- 移除原标题的
t=-10负内边距,防止标题向上偏移导致重叠
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

