如何在Python Dash仪表盘中展示PNG图片与CSV表格?
先安装所需依赖:
pip install dash-table pandas
以下是符合需求的完整代码骨架:
import dash from dash import html, dcc, Input, Output, dash_table import base64 import pandas as pd app = dash.Dash() list_of_images = [ "C:\\Users\\results\\sentiment_plot.png", "C:\\Users\\positive_wc.png", "C:\\Users\\negative_wc.png", "C:\\Users\\top_hashtag.png" ] list_of_data = [ "C:\\Users\\sentiment_by_location.csv", "C:\\Users\\geo_location_frequency.csv", "C:\\Users\\total_hashtag_frequency.csv", ] app.layout = html.Div(children=[ html.H1(children='Twitter analytics Report'), # 图表区域 html.H2(children='Image charts'), html.Button('charts', id='show-charts-btn', n_clicks=0), html.Div(id='charts-container', style={'margin': '20px 0'}), # 数据表格区域 html.H2(children='Data preview'), dcc.Dropdown( id='data-dropdown', options=[{'label': i.split('\\')[-1], 'value': i} for i in list_of_data], value = list_of_data[0] ), html.Div(id='table-container', style={'margin': '20px 0'}) ]) # 点击按钮展示所有图片的回调 @app.callback( Output('charts-container', 'children'), Input('show-charts-btn', 'n_clicks'), prevent_initial_call=True ) def show_all_charts(n_clicks): img_components = [] for img_path in list_of_images: encoded_image = base64.b64encode(open(img_path, 'rb').read()).decode() src = f'data:image/png;base64,{encoded_image}' # 统一设置图片尺寸,可自行调整宽高参数 img_components.append(html.Img( src=src, style={'width': '90%', 'max-height': '600px', 'margin': '15px auto', 'display': 'block'} )) return img_components # 选择CSV后展示前100行表格的回调 @app.callback( Output('table-container', 'children'), Input('data-dropdown', 'value') ) def show_data_table(data_path): df = pd.read_csv(data_path, nrows=100) return dash_table.DataTable( data=df.to_dict('records'), columns=[{"name": i, "id": i} for i in df.columns], style_table={'overflowX': 'auto'}, style_cell={'padding': '8px', 'textAlign': 'left'} ) if __name__ == '__main__': app.run_server(debug=True)
核心功能说明
- 点击
charts按钮后会加载所有PNG图片到页面,所有图片通过style参数统一了展示尺寸,可自行调整宽高参数适配你的页面 - CSV下拉列表默认显示文件名,选中对应文件后会自动读取前100行以表格形式展示,宽表支持横向滚动
- 保留了你原有的本地文件路径配置,无需修改路径即可直接运行调试
内容的提问来源于stack exchange,提问作者Lilly
相关产品推荐
相关产品推荐

