I am trying to learn dash in python with matplotlib images. Below is the code for 2 tabs. I am looking for following functionality:
One tabs generates an image and other tabs should display some text. But I am not able to show text because the output expects an image. How can I correct it ? Below is the code.
import numpy as np
from io import BytesIO
import base64
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
def fig_to_uri(in_fig, close_all=True, **save_args):
"""
Save a figure as a URI
:param in_fig:
:return:
"""
out_img = BytesIO()
in_fig.savefig(out_img, format='png', **save_args)
if close_all:
in_fig.clf()
plt.close('all')
out_img.seek(0) # rewind file
encoded = base64.b64encode(out_img.read()).decode("ascii").replace("\n", "")
return "data:image/png;base64,{}".format(encoded)
app.layout = html.Div([
html.H1(children='Market analysis',
style={'textAlign': 'center'}
),
dcc.Tabs(id='tabs-example', value='tab-1',
vertical=True,
children=[
dcc.Tab(label='Daily Returns', value='tab-1'),
dcc.Tab(label='Hourly Returns', value='tab-2')
]),
html.Div([html.Img(id='tabs-example-content', src='')]),
html.Div(id='tabs-content-example')
])
@app.callback(Output('tabs-example-content', component_property='src'),
[Input('tabs-example', 'value')])
def render_content(value):
if value=='tab-1':
fig, ax1 = plt.subplots(1, 1)
ax1.matshow(np.random.uniform(-1, 1, size=(2, 4)))
out_url = fig_to_uri(fig)
return out_url
elif value == 'tab-2':
return html.Div([html.H3('Tab content 2')])
if __name__ == '__main__':
app.run_server(debug=True)