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
Related
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.
I am new to plotly dash. I am trying to create an interactive dashboard where I can filter the colorbar to see the upper values for example if the value is 3000 it was red, so if I type 3000 as input, it is still red but the graph will not show values less than 3000. I am able to add the filtering option but when I filter(I used zmin in go heatmap) the colorscale also changes. Can I keep the previous colorscale so that if I choose zmin, it refreshes the graph with the original colorscale but filters values greater than zmin? Here is the code I have written so far -
app.layout = html.Div(children=[
html.H1(children='Title'),
dcc.Graph(
id='graph',
figure=fig
),
dcc.Input(
id="input", type="number", value=0
)
])
#app.callback(
Output('graph', 'figure'),
Input('input', 'value')
)
def update_figure(input):
frames = []
for d, i in enumerate(sorted(timestamp_list)):
frames.append(
go.Frame(
name=time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(int(i) / 1000)),
data=[
go.Heatmap(z=df_dict[i],
x=df_dict[i].columns,
y=df_dict[i].index,
zmin=input,
zmax=max(value_list))
]
)
)
yaxis_name = kind.split("_")[0]
xaxis_name = kind.split("_")[1]
fig = go.Figure(
data=frames[0].data,
frames=frames,
layout=go.Layout(
autosize=True,
height=800,
yaxis={"title": yaxis_name, "dtick": 1},
xaxis={"title": xaxis_name, "tickangle": 45, "side": 'top'},
),
)
# finally, create the slider
fig.update_layout(
updatemenus=[{
'buttons': [
{
'args': [None, {'frame': {'duration': 500, 'redraw': True},
'transition': {'duration': 500, 'easing': 'quadratic-in-out'}}],
'label': 'Play',
'method': 'animate'
},
{
'args': [[None], {'frame': {'duration': 0, 'redraw': False},
'mode': 'immediate',
'transition': {'duration': 0}}],
'label': 'Pause',
'method': 'animate'
}
],
'direction': 'left',
'pad': {'r': 10, 't': 100},
'showactive': False,
'type': 'buttons',
'x': 0.1,
'xanchor': 'right',
'y': 0,
'yanchor': 'top'
}],
sliders=[{"steps": [{"args": [[f.name], {"frame": {"duration": 0, "redraw": True},
"mode": "immediate", }, ],
"label": f.name, "method": "animate", }
for f in frames],
}]
)
return fig
Here is the sample output I get-[![enter image description here][1]][1]
After filtering- [![enter image description here][2]][2]
I am not completely sure I understood what you mean, but isn't it enough to just filter your data? I also don't have an example of how you data look like, but why don't you try filtering your data frame before you plot?
data_to_plot = frames[frames['your_column'] > zmin]
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
I am using Dash to graph a dataset which contains columns for x, y, and another column for type of fruit. I have added in a checklist apples and grapes. What I want to do now is have the graph display the values of x and y for grapes if the grapes checkbox is ticked, apples if the apples checkbox is ticked, and both if both are ticked.
Would someone be able to help me? This is a really simple question I know.
I know I need to change the ‘def … return’ part somehow.
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
app = dash.Dash()
fruits = {'Day':[1,2,3,4,5,6],
'Visitors':[43,34,65,56,29,76],
'Bounce_Rate':[65,67,78,65,45,52],
'Nice_Fruits':['apple', 'apple', 'grape', 'apple', 'grape', 'grape']}
df_all_fruits = pd.DataFrame(fruits)
Nice_Fruits_list=df_all_fruits['Nice_Fruits'].unique()
app.layout = html.Div(children=[
html.H1('Payment Curve and predictor'),
html.Label('fruits_1'),
dcc.Checklist(
id='fruits_checklist',
options=[{'label': i, 'value': i} for i in Nice_Fruits_list],
values=['apple', 'grape'],
labelStyle={'display': 'inline-block'}
),
dcc.Graph(
id='fruits_graph',
figure={
'data': [
go.Scatter(
x=df_all_fruits['Visitors'],
y=df_all_fruits['Bounce_Rate'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
)
],
'layout': go.Layout(
xaxis={'type': 'linear', 'title': 'Visitors'},
yaxis={'title': 'Bounce_Rate'},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
hovermode='closest'
)
}
),
])
#app.callback(
Output('fruits_graph', 'figure'),
[Input('fruits_checklist', 'values')]
)
def update_graph(fruits_checklist_value):
df = df_all_fruits[df_all_fruits.Nice_Fruits.isin([fruits_checklist_value])]
return {
'data': [go.Scatter(
x= df['Visitors'],
y= df['Bounce_Rate'],
mode='markers',
marker={
'size': 15,
'opacity': 0.5,
'line': {'width': 0.5, 'color': 'white'}
}
)],
'layout': {'margin': {'l': 40, 'r': 0, 't': 20, 'b': 30}}
}
app.css.append_css({'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'})
if __name__ == '__main__':
app.run_server()
So what you want is update your datas, and that's what you do, but to do so you'll have to put two plot on the same Scatter. You indeed want to modify the return. You need to iterate over the values in the Checkbox. And you then tell the graph to put the two scatters on the same graph:
#app.callback(
Output('fruits_graph', 'figure'),
[Input('fruits_checklist', 'values')]
)
def update_graph(values):
df = df_all_fruits
return {'data': [go.Scatter(
x= df[df['Nice_Fruits']==v]['Visitors'],
y= df[df['Nice_Fruits']==v]['Bounce_Rate'],
mode='markers',
marker={
'size': 15,
'opacity': 0.5,
'line': {'width': 0.5, 'color': 'white'}
}
) for v in values],
'layout': {'margin': {'l': 40, 'r': 0, 't': 20, 'b': 30}}
}
tell me if it solves your issue.
I am going through the the slider animation plot tutorial from plotly (https://plot.ly/python/animations/), the one at the bottom, with my own data. My scenario is basically is data gathered from users from an application. I have data for one month (May), which the frequency of users are recorded hourly for each day. I want to use a slider to have a range of values from day 1 to 31 and the plot to show the unique values of each hour for each specific day.
My problem: I only get day one, but the value of the slider is updating correctly. Fixed old problem, now I have another one: Now instead of 1 step of the data, the graph is showing every single step.
My code:
# dMay to DataFrame
dfMay = pd.DataFrame({key :dMay[key] for key in list(dMay.keys())})
for i, df in enumerate([dfMay], 1):
df.columns = [str(col_name)[6:].format(i) for col_name in df.columns]
keys = list(map(lambda x: str(x), dfMay.keys())) # Slider values - days
from plotly.grid_objs import Grid, Column
listOfCols = []
for col in keys:
listOfCols.append(Column(dfMay[col], col))
grid = Grid(listOfCols)
py.grid_ops.upload(grid, 'Testing'+str(time.time()), auto_open=False)
# Animated Plot
figure = {
'data': [],
'layout': {},
'frames': []
}
# fill in most of layout
figure['layout']['xaxis'] = {'range': [0, 23], 'title': 'Zaman (saat)'}
figure['layout']['yaxis'] = {'title': 'Kullanıcı Sayısı', 'type': 'linear'}
figure['layout']['hovermode'] = 'closest'
figure['layout']['sliders'] = {
'args': [
'transition', {
'duration': 400,
'easing': 'cubic-in-out'
}
],
'initialValue': '0',
'plotlycommand': 'animate',
'values': list(range(24)),
'visible': True
}
figure['layout']['updatemenus'] = [
{
'buttons': [
{
'args': [None, {'frame': {'duration': 500, 'redraw': True},
'fromcurrent': True, 'transition': {'duration': 300, 'easing': 'quadratic-in-out'}}],
'label': 'Play',
'method': 'animate'
},
{
'args': [[None], {'frame': {'duration': 0, 'redraw': True}, 'mode': 'immediate',
'transition': {'duration': 0}}],
'label': 'Pause',
'method': 'animate'
}
],
'direction': 'left',
'pad': {'r': 10, 't': 87},
'showactive': False,
'type': 'buttons',
'x': 0.1,
'xanchor': 'right',
'y': 0,
'yanchor': 'top'
}
]
sliders_dict = {
'active': 0,
'yanchor': 'top',
'xanchor': 'left',
'currentvalue': {
'font': {'size': 20},
'prefix': 'Zaman:',
'visible': True,
'xanchor': 'right'
},
'transition': {'duration': 300, 'easing': 'cubic-in-out'},
'pad': {'b': 10, 't': 50},
'len': 0.9,
'x': 0.1,
'y': 0,
'steps': []
}
# make data
start = 0
for day in keys:
data_dict = {
'x': list(range(24)),
'y': list(dfMay[day]),
'mode': 'markers',
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'size': 20
},
'name': day
}
figure['data'].append(data_dict)
# make frames
for day in keys:
frame = {'data': [], 'name': str(day)}
data_dict = {
'x': list(range(24)),
'y': list(dfMay[day]),
'mode': 'markers',
'text': list(dfMay[day]),
'marker': {
'sizemode': 'area',
'sizeref': 200000,
'size': 20
},
'name': day,
}
frame['data'].append(data_dict)
figure['frames'].append(frame)
slider_step = {'args': [
[day],
{'frame': {'duration': 1000, 'redraw': True},
'mode': 'immediate',
'transition': {'duration': 1000}}
],
'label': day,
'method': 'animate'}
sliders_dict['steps'].append(slider_step)
figure['layout']['sliders'] = [sliders_dict]
print('Done')
plot(figure)
I also can,t get rid of the colored markers on the right!
EDIT 1: Added dfMay Table
EDIT 2: Changed problem, added a new plot
Images to Supplement:
Fixes slider related issue. I followed another plotly tutorial. https://plot.ly/~empet/14896
plotData=[dict(type='scatter',
x=list(range(24)),
y=test_data[:0],
mode='markers',
marker=dict(size=10, color='red')
)
]
frames=[dict(data=[dict(y=test_data[:,k])],
traces=[0],
name=f'{k+1}',
layout=dict(yaxis=dict(range=[-1, test_data[:, k].max()+100]))) for k in range(31)]
sliders=[dict(steps= [dict(method= 'animate',
args= [[ f'{k+1}'],
dict(mode= 'e',
frame= dict( duration=1000, redraw= False ),
transition=dict( duration= 0)
)
],
label=f' {k+1}'
) for k in range(31)],
transition= dict(duration= 30 ),
x=0,#slider starting position
y=0,
currentvalue=dict(font=dict(size=12),
prefix='Day: ',
visible=True,
xanchor= 'center'
),
len=1.0,
active=1) #slider length)
]
axis_style=dict(showline=True,
mirror=True,
zeroline=False,
ticklen=4)
layout=dict(title='Mayıs-Günlük Kullanıcı Sayıları',
width=900,
height=600,
autosize=False,
xaxis=dict(axis_style, dtick=1, tit='s' title='Zaman (saat)', **dict(range=[0,24])),
yaxis=dict(axis_style, title='Kullanıcı Sayısı',autorange=False),
#plot_bgcolor="rgba(66,134,244, 0.2)",
shapes= [dict(
# Sabah
type= 'rect',
xref= 'x',
yref= 'paper',
x0= '0',
y0= 0,
x1= '8',
y1= 1,
fillcolor= 'rgba(66, 134, 244, 0.5)',
opacity= 0.2,
line= dict(width= 0)
),
# Oglen
dict(
type= 'rect',
xref= 'x',
yref= 'paper',
x0= '8',
y0= 0,
x1= '16',
y1= 1,
fillcolor= '#rgba(255, 252, 117,1)',
opacity= 0.2,
line= dict(width=0)
),
# Aksam
dict(
type= 'rect',
xref= 'x',
yref= 'paper',
x0= '16',
y0= 0,
x1= '24',
y1= 1,
fillcolor= 'rgba(2, 0, 168, 1)',
opacity= 0.2,
line= dict(width=0)
)
],
hovermode='closest',
updatemenus=[dict(type='buttons', showactive=True,
y=0,
x=1.15,
xanchor='right',
yanchor='top',
pad=dict(t=0, r=10),
buttons=[dict(label='Play',
method='animate',
args=[None,
dict(frame=dict(duration=4000,
redraw=True),
transition=dict(duration=4000),
fromcurrent=True,
mode='immediadate'
)
]
),
dict(label='Pause',
method='animate',
args=[[None],
dict(frame=dict(duration=0,
redraw=False),
transition=dict(duration=30),
fromcurrent=True,
mode='immediate'
)
]
)
]
)
],
sliders=sliders
)
# Animated Plot
figure = {
'data': plotData,
'layout': layout,
'frames': frames
}
fig=dict(data=plotData, frames=frames, layout=layout)
fig['data'][0].update(mode='markers+lines',
line=dict(width=1.5, color='blue'))
plot(fig, auto_open=False)