You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Can you integrate Matplotlib support for put_image() function i.e. somehow it can accept a Matplotlib figure object and render it nicely? This will open up a range of data science applications.
I know you have Bokeh and Plotly integration but a lot of users are more comfortable with Matplotlib than Bokeh or Plotly.
Actually, I created a simple demo for Matplotlib plots. Here is the code, you can use it in your demo examples.
You may find the function fig2img particularly interesting as it converts a Matplotlib figure object to a PIL.Image.image object.
frompywebio.inputimport*frompywebio.outputimport*frompywebioimportstart_serverimportmatplotlib.pyplotaspltimportnumpyasnpfromPILimportImageimportiodefdata_gen(num=100):
""" Generates random samples for plotting """a=np.random.normal(size=num)
returnadefplot_raw(a):
""" Plots line graph """plt.close()
plt.figure(figsize=(12,5))
plt.plot(a)
returnplt.gcf()
defplot_hist(a):
""" Plots histogram """plt.close()
plt.figure(figsize=(12,5))
plt.hist(a,color='orange',edgecolor='k')
returnplt.gcf()
deffig2img(fig):
""" Convert a Matplotlib figure to a PIL Image and return it """buf=io.BytesIO()
fig.savefig(buf)
buf.seek(0)
img=Image.open(buf)
returnimgdefGenerate(num=100):
""" Generates plot, called from the `Generate` button """remove(scope='raw')
withuse_scope(name='raw',clear=True,) asimg:
a=data_gen(num)
f1=plot_raw(a)
im1=fig2img(f1)
put_image(im1)
f2=plot_hist(a)
im2=fig2img(f2)
put_image(im2)
defapp():
put_markdown(""" # Matplotlib plot demo We show two plots from random gaussian samples - A line plot - A histogram """, strip_indent=4)
num_samples=input("Number of samples", type=NUMBER)
Generate(num_samples)
if__name__=='__main__':
start_server(app,port=9999,debug=True)
Activity
tirthajyoti commentedon May 7, 2021
Actually, I created a simple demo for Matplotlib plots. Here is the code, you can use it in your demo examples.
You may find the function
fig2imgparticularly interesting as it converts a Matplotlib figure object to aPIL.Image.imageobject.wang0618 commentedon May 8, 2021
A more simple version is of
fig2img()is: