如何消除imgkit from_string生成图片右侧的多余留白?
消除Plotly转HTML再转图片后的右侧留白问题
问题描述
使用Plotly的to_html方法导出包含渲染脚本的图表,再通过imgkit的from_string方法将HTML转换为图片字节时,生成的图片右侧存在大量空白,示例如下:

代码示例:
fig = go.Figure(data=[go.Bar( x=[*data_dict.keys()], y=[*data_dict.values()], name='Nodes', marker=dict(color='rgb(128, 0, 128)'), # legendrank=1, )]) # set the x-axis position to the top of the plot fig.update_layout(xaxis=dict( position=0.05, tickangle=-90, tickfont=dict(size=10), tickmode='array', tickvals=['A', 'B', 'C'], )) fig.update_layout( # font_color="white", font=dict(size=18), plot_bgcolor='rgb(0, 0, 0)', title=title, title_x=0.5, title_y=0.9, yaxis_title="Page Rank", showlegend=True, legend=dict( orientation="v", yanchor="top", y=-0.2, xanchor="left", x=0 ), ) # Convert fig.data tuple to a list, sort it based on x-axis value in ascending order, and convert back to a tuple fig.data = tuple(sorted(list(fig.data), key=lambda trace: trace.x[0])) fig.update_xaxes(showgrid=True, gridwidth=0.1, gridcolor='rgb(200, 200, 200)') fig.update_yaxes(showgrid=True, gridwidth=0.1, gridcolor='rgb(200, 200, 200)') # return base64.b64encode(fig.to_image(format='png', width=400, height=400, scale=0)).decode('utf-8') html = fig.to_html( config={'displayModeBar': False, 'staticPlot': True}) img = imgkit.from_string(html, False, options={'format': 'png'}) image = base64.b64encode(img).decode('utf-8')
解决方法
试试这几个方案,能有效消除右侧留白:
1. 给Plotly图表设置明确宽度和边距
在fig.update_layout中添加width和margin参数,直接控制图表的整体尺寸和留白大小:
fig.update_layout( # 保留原有参数... width=800, # 根据需求调整宽度 margin=dict(l=50, r=20, t=80, b=100) # 缩小右侧边距(r参数) )
2. 给imgkit指定渲染宽度
在imgkit的options里添加--width参数,强制图片渲染宽度和图表宽度匹配:
img = imgkit.from_string(html, False, options={'format': 'png', '--width': '800'})
3. 用div包裹HTML限制宽度
把生成的Plotly HTML包裹在固定宽度的div中,让imgkit按这个宽度渲染:
html = f'<div style="width:800px; overflow:hidden;">{fig.to_html(config={"displayModeBar": False, "staticPlot": True})}</div>'
4. 开启Plotly自动适配布局
在update_layout中设置autosize=True,让图表自动根据内容调整宽度,减少冗余空白:
fig.update_layout( # 保留原有参数... autosize=True )
内容的提问来源于stack exchange,提问作者shailesh gavathe
相关产品推荐
相关产品推荐

