为Dash Plotly图表添加可关联回调的自定义导出按钮
自定义Plotly图表导出按钮实现方案
完全可以通过Dash的回调功能实现自定义参数的图表导出,解决Plotly内置导出分辨率低、参数可控性有限的问题。下面是修改后的完整代码,为饼图添加了可配置导出参数的控件和触发按钮:
import dash from dash import dcc, html, Input, Output, State import plotly.graph_objects as go import plotly.io as pio import tempfile import os # 初始化Dash应用 app = dash.Dash(__name__) # 饼图数据 labels = ['A', 'B', 'C', 'D'] values = [15, 30, 45, 10] # 应用布局 app.layout = html.Div([ # 饼图组件 dcc.Graph(id='pie-chart', figure=go.Figure(data=[go.Pie(labels=labels, values=values)])), # 导出参数配置区 html.Div([ html.Div([ html.Label('文件类型:'), dcc.Dropdown( id='export-format', options=[ {'label': 'PNG', 'value': 'png'}, {'label': 'JPEG', 'value': 'jpeg'}, {'label': 'SVG', 'value': 'svg'}, {'label': 'PDF', 'value': 'pdf'} ], value='png' ) ], style={'width': '20%', 'display': 'inline-block', 'margin-right': '20px'}), html.Div([ html.Label('宽度(像素):'), dcc.Input(id='export-width', type='number', value=1200, min=500, max=4000) ], style={'width': '20%', 'display': 'inline-block', 'margin-right': '20px'}), html.Div([ html.Label('高度(像素):'), dcc.Input(id='export-height', type='number', value=800, min=500, max=4000) ], style={'width': '20%', 'display': 'inline-block', 'margin-right': '20px'}), html.Div([ html.Label('分辨率(DPI):'), dcc.Input(id='export-dpi', type='number', value=300, min=72, max=600) ], style={'width': '20%', 'display': 'inline-block', 'margin-right': '20px'}), # 导出触发按钮 html.Button('导出图表', id='export-button', n_clicks=0, style={'margin-top': '22px'}) ], style={'margin': '20px 0'}), # 隐藏的下载组件 dcc.Download(id='download-component') ]) # 导出回调函数 @app.callback( Output('download-component', 'data'), Input('export-button', 'n_clicks'), State('pie-chart', 'figure'), State('export-format', 'value'), State('export-width', 'value'), State('export-height', 'value'), State('export-dpi', 'value'), prevent_initial_call=True ) def export_chart(n_clicks, figure, format_type, width, height, dpi): # 创建临时文件存储导出的图表 with tempfile.NamedTemporaryFile(mode='w+b', suffix=f'.{format_type}', delete=False) as tmp: tmp_path = tmp.name # 使用plotly.io写入自定义参数的图表 pio.write_image( figure, tmp_path, format=format_type, width=width, height=height, scale=dpi/72 # DPI转换为scale参数,72是Plotly默认DPI ) # 返回下载文件 return dcc.send_file(tmp_path, filename=f'pie-chart.{format_type}') if __name__ == '__main__': app.run_server(debug=True)
关键功能说明
- 参数配置控件:通过下拉菜单选择文件类型,输入框设置宽度、高度和分辨率,实现导出参数的完全自定义
- 回调触发逻辑:点击导出按钮后,回调函数获取当前图表状态和配置参数,使用
plotly.io.write_image生成符合要求的图表文件 - 临时文件处理:利用临时文件存储生成的图表,避免服务器文件堆积,导出后通过
dcc.send_file提供下载
注意事项
- 需要提前安装依赖库:
pip install dash plotly kaleido(kaleido是Plotly导出静态图片的必备依赖) - SVG格式不需要DPI参数,代码中仍可兼容设置,实际导出时会自动忽略
内容的提问来源于stack exchange,提问作者jonboy
相关产品推荐
相关产品推荐

