質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
CSV

CSV(Comma-Separated Values)はコンマで区切られた明白なテキスト値のリストです。もしくは、そのフォーマットでひとつ以上のリストを含むファイルを指します。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

963閲覧

Dash csvを読み込みX軸、Y軸を選択式にしたい

chihuahua_house

総合スコア23

CSV

CSV(Comma-Separated Values)はコンマで区切られた明白なテキスト値のリストです。もしくは、そのフォーマットでひとつ以上のリストを含むファイルを指します。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/01/13 12:43

Dashを使ってcsvをアップロードし、グラフを作成するアプリケーションを開発しています。

csvのアップロード後、X軸、Y軸をドロップボックス選択方式で実装したいのですが、
解決できませんでした。

実装方法をご存知の方いましたら、ご教授お願いいたします。

python

1# -*- coding: utf-8 -*- 2import base64 3import datetime 4import io 5import os 6from collections import defaultdict 7 8import dash 9from dash.dependencies import Input, Output, State 10import dash_core_components as dcc 11import dash_html_components as html 12import dash_table 13 14import pandas as pd 15import plotly.graph_objs as go 16 17import pysnooper 18 19external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] 20 21app = dash.Dash(__name__, external_stylesheets=external_stylesheets) 22 23app.config.suppress_callback_exceptions = True 24 25CHART_LIST = sorted([ 26 'Line', 27 'Bar', 28 'Histogram', 29 'Pie', 30 'Polar', 31 'Box', 32 'Heatmap', 33 '3D Scatter', 34 '3D Surface', 35 '2D Histogram', 36]) 37 38# ----------------------------------------------------------------------------------------------------------------------------------------- 39# html部分 40app.layout = html.Div( 41 [ 42 # File upload bunner 43 html.P( 44 """ 45 Dash: A web application framework for Python. 46 """ 47 ), 48 html.H6('Please select a chart type'), 49 dcc.Dropdown(id='chart-type', 50 options=[{ 51 'label': i, 52 'value': i 53 } for i in CHART_LIST], 54 value='Line'), 55 html.H5('x-axis'), 56 dcc.RadioItems(id='xaxis-type', 57 options=[{ 58 'label': i, 59 'value': i 60 } for i in ['linear', 'log', 'category']], 61 value='linear', 62 labelStyle={'display': 'inline-block'}), 63 html.H5('y-axis'), 64 dcc.RadioItems(id='yaxis-type', 65 options=[{ 66 'label': i, 67 'value': i 68 } for i in ['linear', 'log', 'category']], 69 value='linear', 70 labelStyle={'display': 'inline-block'}), 71 html.Div(id='the_graph'), 72 # 列選択部分 73 html.Div(id='output-data-upload'), 74 dcc.Upload( 75 id='upload-data', 76 children=html.Div(['Drag and Drop or ', 77 html.A('Select Files')]), 78 style={ 79 'color' : 'red', 80 'width': '100%', 81 'height': '60px', 82 'lineHeight': '60px', 83 'borderWidth': '1px', 84 'borderStyle': 'dashed', 85 'borderRadius': '5px', 86 'textAlign': 'center', 87 'margin': '10px' 88 }, 89 # Allow multiple files to be uploaded 90 multiple=True), 91 ], ) 92 93# html終了 94# --------------------------------------------------------------------------------------------------------------------------------------------- 95 96@pysnooper.snoop('glaph.log', prefix='data_graph') 97def data_graph( 98 df, 99 filename, 100 chart_type, 101 xaxis_type, 102 yaxis_type, 103): 104 basename = os.path.splitext(filename)[0] 105 # ファイル名の1つ目の'_'で区切って、グラフタイトルとY軸名に分ける 106 if '_' in basename: 107 title, yaxis_name = basename.split('_', 1) 108 # ファイル名に'_'がなければグラフタイトルは固定、Y軸はファイル名 109 else: 110 title, yaxis_name = 'Visualization', basename 111 112 def args(i): 113 """graph_objs helper func""" 114 return {'x': df.index, 'y': df[i], 'name': i} 115 116 data = { 117 'Line': [go.Scatter(args(i)) for i in df.columns], 118 'Bar': [go.Bar(args(i)) for i in df.columns], 119 'Histogram': 120 [go.Histogram(x=df[i], name=i, opacity=.5) for i in df.columns], 121 'Pie': [ 122 go.Pie(labels=df.index, 123 values=df[i], 124 name=i, 125 domain={'column': list(df.columns).index(i)}) 126 for i in df.columns 127 ], 128 'Polar': [ 129 go.Scatterpolar( 130 r=df[i], 131 theta=df.index, 132 name=i, 133 ) for i in df.columns 134 ], 135 'Heatmap': [go.Heatmap(x=df.index, y=df.columns, z=df.values)], 136 'Box': [go.Box(y=df[i], name=i) for i in df.columns], 137 '3D Scatter': [ 138 go.Scatter3d(x=df.index, y=df.columns, z=df[i], name=i) 139 for i in df.columns 140 ], 141 '3D Surface': [ 142 go.Surface(x=df.index, 143 y=df.columns, 144 z=df.values, 145 name=yaxis_name, 146 contours=go.surface.Contours( 147 z=go.surface.contours.Z(show=True, 148 usecolormap=True, 149 highlightcolor="#42f462", 150 project=dict(z=True)))), 151 ], 152 '2D Histogram': [go.Histogram2d(x=df.iloc[:, 0], y=df.iloc[:, 1])] 153 } 154 155 layout = defaultdict( 156 # default layout 157 lambda: go.Layout(title=go.layout.Title(text=title), 158 xaxis={ 159 'type': xaxis_type, 160 'title': df.index.name, 161 'rangeslider': dict(visible=False), 162 }, 163 yaxis={ 164 'type': yaxis_type, 165 'title': yaxis_name, 166 }, 167 margin={ 168 'l': 60, 169 'b': 50 170 }, 171 hovermode='closest'), 172 # other layout 173 { 174 'Histogram': 175 go.Layout(title=title, 176 xaxis={'title': 'Value'}, 177 yaxis={'title': 'Count'}, 178 barmode='overlay', 179 hovermode='closest'), 180 'Pie': 181 go.Layout(title=go.layout.Title(text=title), 182 grid={ 183 'columns': len(df.columns) - 1, 184 'rows': 1 185 }, 186 hovermode='closest') 187 }) 188 return dcc.Graph(id='the_graph', 189 figure={ 190 'data': data[chart_type], 191 'layout': layout[chart_type] 192 }) 193 194@pysnooper.snoop('column.log') 195def parse_contents(contents, filename, date, chart_type, xaxis_type, 196 yaxis_type): 197 content_type, content_string = contents.split(',') 198 199 decoded = base64.b64decode(content_string) 200 try: 201 if 'csv' in filename: 202 df = pd.read_csv(io.StringIO(decoded.decode('utf-8')), 203 index_col=0, 204 parse_dates=True) 205 elif 'xls' in filename: 206 df = pd.read_excel(io.BytesIO(decoded), 207 index_col=0, 208 parse_dates=True) 209 except Exception as e: 210 print(e) 211 return html.Div(['There was an error processing this file.']) 212 213 return html.Div([ 214 html.Div([ 215 dcc.Dropdown( 216 id='xaxis-column', 217 options=[{'label': i, 'value': i} for i in df.columns], 218 value='Fertility rate, total (births per woman)' 219 ), 220 ],style={'width': '49%', 'display': 'inline-block'}), 221 html.Div([ 222 dcc.Dropdown( 223 id='yaxis-column', 224 options=[{'label': i, 'value': i} for i in df.columns], 225 value='Fertility rate, total (births per woman)' 226 ), 227 ],style={'width': '49%', 'float': 'right', 'display': 'inline-block'}), 228 data_graph(df, filename, chart_type, xaxis_type, yaxis_type), 229 html.Hr(), # horizontal line 230 231 html.Div('Raw Content'), 232 html.Pre(contents[0:200] + '...', 233 style={ 234 'whiteSpace': 'pre-wrap', 235 'wordBreak': 'break-all' 236 }) 237 ]) 238 239 240@app.callback(Output( 241 'output-data-upload', 242 'children', 243), [ 244 Input('upload-data', 'contents'), 245 Input('chart-type', 'value'), 246 Input('xaxis-type', 'value'), 247 Input('yaxis-type', 'value'), 248], [State('upload-data', 'filename'), 249 State('upload-data', 'last_modified')]) 250 251@pysnooper.snoop('Dash.log', prefix='main ') 252def update_output(list_of_contents, chart_type, xaxis_type, yaxis_type, 253 list_of_names, list_of_dates): 254 255 if list_of_contents is not None: 256 children = [ 257 parse_contents(c, n, d, chart_type, xaxis_type, yaxis_type) 258 for c, n, d in zip(list_of_contents, list_of_names, list_of_dates) 259 ] 260 return children 261 262 263if __name__ == '__main__': 264 app.run_server(debug=True) 265

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問