Modify option in plotter / Add new method of popup

This commit is contained in:
Sirin Puenggun 2023-05-11 20:39:28 +07:00
parent 349e08d2e4
commit 791c0a588d

View File

@ -1,10 +1,13 @@
import webbrowser
import os
import plotly.graph_objects as go
import plotly.io as pio
import tempfile
import tkinter as tk
import webview
from PIL import Image, ImageTk
class plotter:
def nutrient_plotter(self, df, row_index, nutrient_indices, chart_type, popup=True, to_html_str=False):
def nutrient_plotter(self, df, row_index, nutrient_indices, chart_type, popup=True, frame=None):
"""
Generate and display a Plotly graph of nutrient values for a specific row in a DataFrame.
@ -13,6 +16,7 @@ class plotter:
row_index (int): The index of the row in the DataFrame to plot.
nutrient_indices (list of int): The column indices of the nutrients to plot.
chart_type (str): The type of chart to generate ('bar' or 'pie').
popup (bool): to ask if you want to popup new webview window or embed to gui
Returns:
bytes (html_encoded string)
@ -22,18 +26,6 @@ class plotter:
Usage:
nutrient_plotter(df, 0, [16, 18, 20, 22], 'bar')
NOTE: To embed in tkinter use this code block
```py
import io
from PIL import Image
en_html = nutrient_plotter(df, 1, [16, 18, 20, 22], 'bar', to_html_str=True)
stream = io.BytesIO(str_html)
image = Image.open(stream)
photo = tk.PhotoImage(image)
label = tk.Label(root, image=photo)
label.pack()
```
"""
@ -43,11 +35,11 @@ class plotter:
if chart_type == 'bar':
fig = go.Figure(data=go.Bar(x=nutrient_names, y=nutrient_values, marker_color='skyblue'))
fig.update_layout(title=f'Nutrient Values for {product_name}', xaxis_title='Nutrients',
fig.update_layout(xaxis_title='Nutrients',
yaxis_title='Value')
elif chart_type == 'pie':
fig = go.Figure(data=go.Pie(labels=nutrient_names, values=nutrient_values))
fig.update_layout(title=f'Nutrient Composition for {product_name}')
# fig.update_layout(title=f'Nutrient of {product_name}')
else:
raise ValueError('Invalid chart type. Please choose either "bar" or "pie".')
@ -58,9 +50,17 @@ class plotter:
with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as temp:
filename = temp.name
temp.write(encoded_html)
webbrowser.open(filename)
if to_html_str:
return encoded_html
webview.create_window('Nutrients Graph', filename)
webview.start()
else:
fig.update_layout(width=250, height=300)
temp_dir = tempfile.mkdtemp()
image_path = os.path.join(temp_dir, "plot.jpeg")
fig.write_image(image_path, format="jpeg")
label = tk.Label(frame)
img = Image.open(image_path)
label.img = ImageTk.PhotoImage(img)
label['image'] = label.img
label.pack()
# print(type(nutrient_plotter(df, 1, [16, 18, 20, 22], 'bar', False, True)))