Dashboard view side by side using python - python

I am new to python and trying to create dashboard and i want the graph to view side by side instead of one below another.
app = dash.Dash()
app.layout = html.Div(children=[
html.H1('Premium Dash Board'),
html.Div(children='Premium Queue'),
html.Div([
dcc.Graph(id='example',
figure={
'data':[
{'x': ASIN, 'y': Quan, 'type': 'bar', 'name': 'Quantity'},
{'x': ASIN, 'y':List_price, 'type': 'bar', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
}),
],style={'display': 'inline-block'}),
html.Div([
dcc.Graph(id='example1',
figure={
'data': [
{'x': ASIN, 'y': Quan, 'type': 'line', 'name': 'Quantity'},
{'x': ASIN, 'y': List_price, 'type': 'line', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
})
], style={'display': 'inline-block'})
],style={'width': '100%', 'display': 'inline-block'})
Please advise how to proceed.

If I run code on big monitor then I see plots side by side.
If I use smaller window then it automatically put second plot below.
But using 'width': '50%' I can get two plots side by side
import dash
import dash_html_components as html
import dash_core_components as dcc
import random
random.seed(0)
ASIN = list(range(100))
Quan = [random.randint(0, 100) for x in range(100)]
List_price = [random.randint(0, 100) for x in range(100)]
app = dash.Dash()
app.layout = html.Div(children=[
html.H1('Premium Dash Board'),
html.Div(children='Premium Queue'),
html.Div([
dcc.Graph(id='example',
figure={
'data':[
{'x': ASIN, 'y': Quan, 'type': 'bar', 'name': 'Quantity'},
{'x': ASIN, 'y': List_price, 'type': 'bar', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
}),
],style={'width': '50%','display': 'inline-block'}),
html.Div([
dcc.Graph(id='example1',
figure={
'data': [
{'x': ASIN, 'y': Quan, 'type': 'bar', 'name': 'Quantity'},
{'x': ASIN, 'y': List_price, 'type': 'bar', 'name': 'Price'}
],
'layout': {
'title': 'ASIN vs Inventory & Price'
}
})
],style={'width': '50%','display': 'inline-block'}),
])
app.run_server()
TO create this image I used DevTools in Firefox and function to test page with devices which have different screen size - Ctrl+Shift+M

Related

offset annotations on dash/plotly bar chart

This is made using Dash.
I'm trying to move the annotations (number values for each bar) up 10px so I can read them.
I've tried marker, yshift (and a few others I cant recall) but none of them are seen as valid.
Cut down code:
import dash
from dash import dcc, html
from dash.dependencies import Output, Input
import pandas as pd
import csv
app.layout = html.Div([
#order of charts here affects display on page
#html.H1("USDT Market Percent change 5m, 1h, 24h"),
dcc.Graph(id='chart'),
html.Div(children=[
dcc.Graph(id='bar2', style={'display': 'inline-block'}),
dcc.Graph(id='bar', style={'display': 'inline-block'}),
]),
#dcc.Graph(id='chart2'),
dcc.Interval(id='interval', interval=29000, n_intervals=0),
])
def update_bar(value):
# Get the most recent value for columns 11-17
df = import_data()
most_recent = list(df.iloc[-1, 14:24])
previous = list(df.iloc[-2, 14:24])
last_update = df.iloc[-1, 0]
title = f"Percent Change Distribution \n "
fig = {
'data': [
{'x': df.columns[14:24], 'y': most_recent, 'type': 'bar'}
],
'layout': {
'title': title,
'xaxis': {'title': "% ranges", 'tickangle': 90, 'tickfont': {'size': 14, 'weight': 'bold'}},
'yaxis': {'title': "Number"},
'height': 450,
'width': 500,
'annotations': [
{'x': df.columns[14], 'y': most_recent[0], 'text': f" {most_recent[0]}", 'showarrow': False, 'font': {'size': 14, 'weight': 'bold'} },
{'x': df.columns[15], 'y': most_recent[1], 'text': f" {most_recent[1]}", 'showarrow': False },
{'x': df.columns[16], 'y': most_recent[2], 'text': f" {most_recent[2]}", 'showarrow': False },
{'x': df.columns[17], 'y': most_recent[3], 'text': f" {most_recent[3]}", 'showarrow': False },
{'x': df.columns[18], 'y': most_recent[4], 'text': f" {most_recent[4]}", 'showarrow': False },
{'x': df.columns[19], 'y': most_recent[5], 'text': f" {most_recent[5]}", 'showarrow': False },
{'x': df.columns[20], 'y': most_recent[6], 'text': f" {most_recent[6]}", 'showarrow': False },
{'x': df.columns[21], 'y': most_recent[7], 'text': f" {most_recent[7]}", 'showarrow': False },
{'x': df.columns[22], 'y': most_recent[8], 'text': f" {most_recent[8]}", 'showarrow': False },
{'x': df.columns[23], 'y': most_recent[9], 'text': f" {most_recent[9]}", 'showarrow': False },
]
}
}
return fig
I'd be very grateful for any clues.

Adding Horizontal Line to Dash-Plotly Python Dashboard

I am creating a Dash app in Python3. Trying to add in a horizontal line to a bar graph. The examples in the documentation are for line graphs, which have numeric x and y axis, whereas I have a categorical X-axis. The below code creates the graph successfully, but does not show the shape object. How can I add a horizontal line to this graph?
html.Div(
[ dcc.Graph(
id='example-graph-23',
figure={
'data': [
{'x': ['Overall', 'NBA', 'WWC', 'NFL'], 'y': [3,2,2.5],
'type': 'bar', 'name': 'Instagram'},
],
'layout': {
'yaxis' : dict(
range=[0, 4]
),
'plot_bgcolor': colors['background'],
'paper_bgcolor': colors['background'],
'font': {
'color': colors['text']
},
'shapes' : dict(type="line",
x0=0,
y0=2,
x1=5,
y1=2,
line=dict(
color="Red",
width=4,
dash="dashdot",
))
}
}
) ]
, className="four columns"
),
You can add a vertical line by adding x and y coordinates to the figure.data like this:
import dash
import dash_html_components as html
import dash_core_components as dcc
app = dash.Dash()
colors = {'background': 'white', 'text': 'black'}
app.layout = html.Div(
[ dcc.Graph(
id='example-graph-23',
figure={
'data': [
{'x': ['Overall', 'NBA', 'WWC', 'NFL'], 'y': [3,2,2.5],
'type': 'bar', 'name': 'Instagram'},
{'x': ['Overall', 'Overall'], 'y': [0, 4],
'type': 'line', 'name': 'v_line_1'},
{'x': ['NBA', 'NBA'], 'y': [0, 4],
'type': 'line', 'name': 'v_line_2'},
{'x': ['WWC', 'WWC'], 'y': [0, 4],
'type': 'line', 'name': 'v_line_3'},
],
'layout': {
'yaxis' : dict(
range=[0, 4]
),
'plot_bgcolor': colors['background'],
'paper_bgcolor': colors['background'],
'font': {
'color': colors['text']
},
'shapes' : dict(type="line",
x0=0,
y0=2,
x1=5,
y1=2,
line=dict(
color="Red",
width=4,
dash="dashdot",
))
}
}
)], className="four columns"
)
if __name__ == '__main__':
app.run_server(debug=True)
enter image description here

Changing Dash chart series colors

I'm just starting to learn to use Dash and currently have a chart up displaying user engagement on my website. However,
I can't seem to figure out how to style Dash components when it comes to colors and the Dash documentation doesn't seem to have anything on the topic. How do I change a series' colors from the default blue/orange/green? The code for the graph in question is below`
dcc.Graph(
id='average_engagement_graph',
figure={
'data': [
{'x': list(avg_df['day']), 'y': list(avg_df['countMessageIn']),
'type': 'bar', 'name': 'Incoming Messages from Users'},
{'x': list(avg_df['day']), 'y': list(avg_df['countMessageOut']),
'type': 'bar', 'name': 'Outgoing Message by Bot'},
],
'layout': {
'title': 'Average User-Bot Engagement by Day of Week',
'xaxis': {
'title': 'Day of the Week'
},
'yaxis': {
'title': 'Average Number of Messages'
},
}
}
),
For bar, you've got to add it to a key named marker.
dcc.Graph(
id='average_engagement_graph',
figure={
'data': [
{'x': list(avg_df['day']), 'y': list(avg_df['countMessageIn']),
'type': 'bar', 'name': 'Incoming Messages from Users'},
'marker' : { "color" : your_color_array}
{'x': list(avg_df['day']), 'y': list(avg_df['countMessageOut']),
'type': 'bar', 'name': 'Outgoing Message by Bot'},
'marker' : { "color" : your_color_array}
],
'layout': {
'title': 'Average User-Bot Engagement by Day of Week',
'xaxis': {
'title': 'Day of the Week',
},
'yaxis': {
'title': 'Average Number of Messages'
},
}
}
),
EDIT
It seems they have done a lot of edit and you can also do this...
colors = ['lightslategray',] * 5
colors[1] = 'crimson'
fig = go.Figure(data=[go.Bar(
x=['Feature A', 'Feature B', 'Feature C',
'Feature D', 'Feature E'],
y=[20, 14, 23, 25, 22],
marker_color=colors # marker color can be a single color value or an iterable
)])

Python dash call back function

This maybe asking alot, but I was curious if anyone had any tips for combining these two dash scripts. The purpose would be to incorporate the drop down menu to remove/add data points on the visualization plots.
The first script will visualize my data nicely and the second script with the callback function is for creating a drop down menu from the plotly tutorials.
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv('boilerData.csv', index_col='Date', parse_dates=True)
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
app.layout = html.Div([
dcc.Graph(
id='hws',
figure={
'data': [
{'x': df.index, 'y': df.HWST, 'type': 'line', 'name': 'hwst'},
{'x': df.index, 'y': df.HWRT, 'type': 'line', 'name': 'hwrt'},
{'x': df.index, 'y': df.OAT, 'type': 'line', 'name': 'oat'},
],
'layout': {
'title': 'Heating System Data Visualization'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
dropdown script:
import dash
import dash_html_components as html
import dash_core_components as dcc
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Outdoor Temp', 'value': 'OAT'},
{'label': 'Hot Water Supply Temp', 'value': 'HWST'},
{'label': 'Hot Water Return Temp', 'value': 'HWRT'}
],
value=['OAT','HWST','HWRT'],
multi=True
),
html.Div(id='output-container')
])
#app.callback(
dash.dependencies.Output('output-container', 'children'),
[dash.dependencies.Input('my-dropdown', 'value')])
def update_output(value):
return 'You have selected "{}"'.format(value)
if __name__ == '__main__':
app.run_server(debug=True)
Any tips help, still learning...
What you need to know is that the callback takes Input from some Dash element (here the value of the dropdown) and returns to Output for some property of another Dash element (here the figure from the graph; notice we only change the data property).
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
import numpy as np
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv('boilerData.csv', index_col='Date', parse_dates=True)
df = df.fillna(method = 'ffill').fillna(method = 'bfill')
app.layout = html.Div([
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Outdoor Temp', 'value': 'OAT'},
{'label': 'Hot Water Supply Temp', 'value': 'HWST'},
{'label': 'Hot Water Return Temp', 'value': 'HWRT'}
],
value=['OAT','HWST','HWRT'],
multi=True
),
dcc.Graph(
id='hws',
figure={
'data': [
{'x': df.index, 'y': df.HWST, 'type': 'line', 'name': 'hwst'},
{'x': df.index, 'y': df.HWRT, 'type': 'line', 'name': 'hwrt'},
{'x': df.index, 'y': df.OAT, 'type': 'line', 'name': 'oat'},
],
'layout': {
'title': 'Heating System Data Visualization'
}
}
)
])
#app.callback(
dash.dependencies.Output('hws', 'figure'),
[dash.dependencies.Input('my-dropdown', 'value')])
def update_output(columns):
return {"data": [{'x': df.index, 'y': df[col], 'type':'line', 'name': col}
for col in columns]}
if __name__ == '__main__':
app.run_server(debug=True)

Getting an Error Using Dash for Figure as Invalid argument `figure.layout` passed into Graph, Expected `object`. Was supplied type `array`

I am trying a code to plot some data using dash and I am thinking, I am doing it right. But not sure why getting a very peculiar message ( plotly 3.8.1 and dash 0.42)
The error message I am getting is :
Invalid argument figure.layout passed into Graph with ID “graph-with-slider”. Expected object. Was supplied type array.
I have created an output which is working fine and giving data and the problem is in the layout and figure call. whicj I am not understanding.
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
#
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)
server = app.server
app.config['suppress_callback_exceptions'] = True
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True
#
app.layout = html.Div([
html.Div([
html.H1('Testing Phase', style = {'text-align': 'center'}),
html.H5('Enter ID'),
dcc.Dropdown(
id = 'id',
style = {'width': '250px'},
options = [
{'label': 'AA', 'value': 'AA'},
{'label': 'AC', 'value': 'AC'},
{'label': 'UQ', 'value': 'UQ'},
{'label': 'NT', 'value': 'NT'},
{'label': 'PQ', 'value': 'PQ'}],
value = 'AA'
),
html.H5('Enter Zone Yield Item'),
dcc.Dropdown(
id = 'mz',
style = {'width': '200px'},
options = [
{'label': 'E1', 'value': 'E1'},
{'label': 'E2', 'value': 'E2'},
{'label': 'E3', 'value': 'E3'},
{'label': 'E4', 'value': 'E4'},
{'label': 'E5', 'value': 'E5'},
{'label': 'E6', 'value': 'E6'}],
value = 'E1'
),
html.Br(),
html.Br(),
html.Button(
id = 'submit',
n_clicks = 0,
children = 'Submit'
),
html.Br(),
html.Br(),
html.Div([
dcc.Graph(
id='mygraph'
),
]),
html.Br(),
html.Br(),
])
])
])
#app.callback(Output('mygraph', 'figure'),
[Input('submit', 'n_clicks')],
[State('pid', 'value'), State('mz', 'value')])])
def update_figure(n_clicks, pid, zone):
mydf = SomeFuncFunc(id, zone)
fit_data = mydf[0]
l_col = fit_data.columns[2]
z_col = fit_data.columns[3]
z2_col = fit_data.columns[4]
l1_v = str(l_col)
z1_v = str(z_col)
print("Starting Trace")
fits = []
fits.append(go.Scatter(
x = fit_data[l_col],
y = fit_data[z_col],
mode = 'markers',
opacity = 0.9,
marker = {
'size': 20, 'symbol': "hexagon", "color": "orange",
'line': {'width': 0.5, 'color': 'white'}
},
name = z1_v + "_" + "Plot",
)),
fits.append(go.Scatter(
x = fit_data[l_col],
y = fit_data[z2_col],
mode = 'markers',
opacity = 0.9,
marker = {
'size': 20, 'symbol': "diamond-open-dot", "color": "blue",
'line': {'width': 0.9, 'color': 'red'}
},
name = z1_v + "_" + "Fit",
)),
mylayout = go.Layout(
width = 800,
height = 500,
xaxis = {'title': 'X axis'},
yaxis = {'title': 'Y axis'}
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend = {'x': 0, 'y': 1},
hovermode = 'closest'
),
fig = {'data': fits, 'layout':mylayout}
return fig
if __name__ == '__main__':
app.run_server(debug = True, port=8053) #
It should plot the data. If I do not include layout, it is plotting, but not always.
The Error Details:
(This error originated from the built-in JavaScript code that runs Dash apps. Click to see the full stack trace or open your browser's console.)Error: Invalid argument `figure.layout` passed into Graph with ID "graphid".
Expected `object`.
Was supplied type `array`.
at propTypeErrorHandler (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/dash_renderer.dev.js?v=0.23.0&m=1557158783:40947:5)
at CheckedComponent (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/dash_renderer.dev.js?v=0.23.0&m=1557158783:37306:9)
at Td (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:82:9)
at be (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:91:477)
at hi (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:104:140)
at Qg (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:144:287)
at Rg (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:145:166)
at Sc (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:158:109)
at Z (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:156:492)
at Kc (http://127.0.0.1:8053/_dash-component-suites/dash_renderer/react-dom#16.8.6.min.js?v=0.23.0&m=1557158783:155:69)
Figured the problem is due to the comma at the end of layout, which triggered the graph layout to be taken as an array instead of object. It is working fine now.

Categories

Resources