I am trying to create a sorting visualizer.
I am able to implement the live changing graph in jupyter notebook, but I am failing to understand where exactly I should call my function.
Or how can the dcc.Interval help me in this regard
Here is the code:
import dash
import dash_core_components as dcc
import dash_html_components as html
from datetime import datetime, timedelta
import dash_table
from dash.dependencies import Input, Output
import plotly_express as px
import random
import plotly.graph_objects as go
import time
app = dash.Dash(__name__)
app.title = "Sorting Visualizer"
server = app.server
colors = {
'background': '#111111',
'text': '#BEBEBE',
'grid': '#333333'
}
the_colors = ['lightslategray', ]*10
the_nums = [random.randint(1, 100) for i in range(0, 10)]
fig = go.Figure()
fig.add_trace(go.Bar(
y = the_nums,
marker_color = the_colors)
)
fig.update_layout(
xaxis={'title': 'NUMBERS ','fixedrange':True},
font=dict(color=colors['text']),
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'],
height = 600,
width = 1200,
hovermode='closest',
showlegend=True,
)
app.layout = html.Div(
id = "sorting_layout",
children = [
dcc.Graph(id = 'new_sorter', figure = fig),
dcc.Interval(
id='interval-component',
interval=1*1000, # in milliseconds
n_intervals=0)
])
#sort1(fig.data[0],fig.layout,10, the_colors)
if __name__ == '__main__':
app.run_server(debug=False)
sort1(fig.data[0],fig.layout,10, the_colors)
And the code for basic bubble sort which works by showing changes in colors is:
def sort1(bar, layout, num, colors):
data = list(bar['y'])
count = 0
for i in range(num):
for j in range(num-i-1):
if data[j] > data[j+1]:
colors[j] = 'blue'
colors[j+1] = 'blue'
fig.update
time.sleep(0.1)
bar['marker']['color'] = colors
data[j], data[j+1] = data[j+1], data[j] # interchange the value
bar['y'] = data # resend the new data list, after updations
time.sleep(0.1)
else:
colors[j] = 'green'
colors[j+1] = 'green'
time.sleep(0.1)
bar['marker']['color'] = colors # keep sending the updated colors list whe changed
time.sleep(0.1)
# current operations are done go back to default color
colors[j] = 'lightslategray'
colors[j+1] = 'lightslategray'
bar['marker']['color'] = colors
count = count + 1
layout.xaxis.title.text = "Number of operations: " + str(count)
colors[num-i-1] = 'red' # done with this guy
bar['marker']['color'] = colors # udpated it back
return fig
I am just getting started with Dash and plotly, so pardon me for any begineer mistakes