我已经为带有Celluloid的BubbleSort制作了动画,并希望将该动画带入Plotly Dash。
这是BubbleSort代码:
from vizualizer import Plot
from plotly.tools import mpl_to_plotly
def bubbleSort(data):
# loop throught all data elements
for l in range(len(data)):
# Compare all elements
for i in range(len(data)):
if i < (len(data)) - 1:
if data[i] > data[i + 1]:
# swap numbers
data[i], data[i + 1] = data[i + 1], data[i]
Plot(i + 1, data)
这是动画代码:
import matplotlib.pyplot as plt
from celluloid import Camera
fig = plt.figure()
camera = Camera(fig)
def Plot(highlight,data):
x = list(range(len(data)))
colors = list(len(data) * 'k')
colors[highlight] = 'r'
plt.bar(x, data, color=colors)
#plt.scatter(x, data, color=colors)
camera.snap()
最后是完整的破折号
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
from vizualizer import camera
import random
from bubbleSort import bubbleSort
from plotly.tools import mpl_to_plotly
size = 30
data = random.sample(range(size), size)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.H1(children='Hands on Python Sorting Algorithm',
style={'text-align': 'center'}),
html.Br(),
dcc.Tabs(className='four.columns', id='tabs', value='tab-1', children=[
dcc.Tab(label='Bubble Sort', value='tab-1'),
dcc.Tab(label='Merge Sort', value='tab-2'),
dcc.Tab(label='Quick Sort', value='tab-3'),
dcc.Tab(label='Heap Sort', value='tab-4'),
],
style={'align-items':'center'}
),
html.Div(id='tabs-content')
])
@app.callback(Output('tabs-content', 'children'),
[Input('tabs', 'value')])
def render_content(tab):
if tab == 'tab-1':
return html.Div([
html.H3('Bubble Sort'),
html.P('Here goes the description for the Bubble Sort'),
dcc.Graph(id='test', figure=bubbleSort(data))
])
elif tab == 'tab-2':
return html.Div([
html.H3('Merge Sort'),
html.P('Here goes the description for the Merge Sort')
])
elif tab == 'tab-3':
return html.Div([
html.H3('Quick Sort'),
html.P('Here goes the description for the Quick Sort')
])
elif tab == 'tab-4':
return html.Div([
html.H3('Heap Sort'),
html.P('Here goes the description for the Heap Sort')
])
if __name__ == '__main__':
app.run_server(debug=False)
我认为我可以制作一个Graph component
并调用bubbleSort(data)
函数进行绘图。
但是我收到了RuntimeError: main thread is not in main loop
错误。
是否可以将动画图绘制为破折号?
如果是,那么最好的方法是什么?