Matplotlib support for put_image
?
#238
Unanswered
tirthajyoti
asked this question in
Q&A
Replies: 2 comments 1 reply
-
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 from pywebio.input import *
from pywebio.output import *
from pywebio import start_server
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import io
def data_gen(num=100):
"""
Generates random samples for plotting
"""
a = np.random.normal(size=num)
return a
def plot_raw(a):
"""
Plots line graph
"""
plt.close()
plt.figure(figsize=(12,5))
plt.plot(a)
return plt.gcf()
def plot_hist(a):
"""
Plots histogram
"""
plt.close()
plt.figure(figsize=(12,5))
plt.hist(a,color='orange',edgecolor='k')
return plt.gcf()
def fig2img(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)
return img
def Generate(num=100):
"""
Generates plot, called from the `Generate` button
"""
remove(scope='raw')
with use_scope(name='raw',clear=True,) as img:
a = data_gen(num)
f1 = plot_raw(a)
im1 = fig2img(f1)
put_image(im1)
f2 = plot_hist(a)
im2 = fig2img(f2)
put_image(im2)
def app():
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) |
Beta Was this translation helpful? Give feedback.
0 replies
-
A more simple version is of def fig2img(fig):
"""
Convert a Matplotlib figure to a bytes and return it
"""
buf = io.BytesIO()
fig.savefig(buf)
return buf.getvalue() |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Can you integrate Matplotlib support for
put_image()
function i.e. somehow it can accept a Matplotlibfigure
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.
Beta Was this translation helpful? Give feedback.
All reactions