首页 > 解决方案 > Dash - 上传 CSV 并呈现图表

问题描述

我是 Dash 的新手,正在尝试学习如何做一个看似非常微不足道的功能:上传 CSV 并将其用作数据框。大多数示例显示引用本地 csv 文件。我不确定下一步是让 Dash 引用我在 CSV 中上传的数据。到目前为止,我编写的代码允许用户上传 CSV 文件并呈现一个表格。接下来应该是从 CSV 文件中选择特定的列并生成一个简单的折线图。任何建议表示赞赏!

import dash_html_components as html
import dash_core_components as dcc
import dash

import plotly
import dash_table_experiments as dte
from dash.dependencies import Input, Output, State

import pandas as pd
import numpy as np

import json
import datetime
import operator
import os

import base64
import io

app = dash.Dash()

app.scripts.config.serve_locally = True
app.config['suppress_callback_exceptions'] = True

app.layout = html.Div([

 html.H5("Upload Files"),
 dcc.Upload(
    id='upload-data',
    children=html.Div([
        'Drag and Drop or ',
        html.A('Select Files')
    ]),
    style={
        'width': '100%',
        'height': '60px',
        'lineHeight': '60px',
        'borderWidth': '1px',
        'borderStyle': 'dashed',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '10px'
    },
    multiple=False),


html.Br(),
html.H5('filename'),
html.Div(dte.DataTable(rows=[{}], id='table'))

])


# Functions

# file upload function
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')

decoded = base64.b64decode(content_string)
try:
    if 'csv' in filename:
        # Assume that the user uploaded a CSV file
        df = pd.read_csv(
            io.StringIO(decoded.decode('utf-8')))
    elif 'xls' in filename:
        # Assume that the user uploaded an excel file
        df = pd.read_excel(io.BytesIO(decoded))

except Exception as e:
    print(e)
    return None

return df


# callback table creation
@app.callback(Output('table', 'rows'),
          [Input('upload-data', 'contents'),
           Input('upload-data', 'filename')])
def update_output(contents, filename):
    if contents is not None:
        df = parse_contents(contents, filename)
        if df is not None:
        return df.to_dict('records')
           else:
             return [{}]
    else:
      return [{}]

# callback Graph Creation - not sure how to reference the csv file that was 
uploaded.  Just want to create a simple line graph or scatter plot with two 
of the variables in the file


app.css.append_css({
   "external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"
})

if __name__ == '__main__':
    app.run_server(debug=True)

标签: pythonplotly-dash

解决方案


推荐阅读