Trying to utilize matplotlib in dash alongside flask. However, when using a callback to generate my matplot and update an image component, I will get if self._tk.getboolean(self._tk.call("info", "exists", self._name)): RuntimeError: main thread is not in main loop
. I’m not experienced with how dash handles threading or implements tkinter GUI. Any help here?
Here is my component:
html.Img(id='pcolormesh-plot')
and the callback:
@callback(
Output('pcolormesh-plot', 'src'),
Input('range-slider', 'value')
)
def plot_data(rangeVal):
# filter data based on user selection
low, high = rangeVal
mask = (df_pos['timestamp'] >= low) & (df_pos['timestamp'] <= high)
df_pos_time = df_pos[mask]
x, y = df_pos_time.x, df_pos_time.y
#KDE
k = gaussian_kde(np.vstack([x, y]))
xi, yi = np.mgrid[x.min():x.max():x.size**0.5*1j,y.min():y.max():y.size**0.5*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))
#build heatmap
fig, ax = plt.subplots()
p = ax.pcolormesh(xi, yi, zi.reshape(xi.shape), alpha=0.6, edgecolor='none', shading='nearest')
ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min(), y.max())
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
alphas = Normalize(0, .3, clip=True)(np.abs(zi.reshape(xi.shape)))
buf = io.BytesIO() # in-memory files
plt.savefig(buf, format = "png") # save to the above file object
plt.close()
data = base64.b64encode(buf.getbuffer()).decode("utf8") # encode to html elements
return "data:image/png;base64,{}".format(data)