Spaces:
Sleeping
Sleeping
Create graph_tool.py
Browse files- graph_tool.py +48 -0
graph_tool.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
from io import BytesIO
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
def generate_plot(data, labels, plot_type, title, x_label="", y_label=""):
|
| 7 |
+
"""
|
| 8 |
+
Generates a plot (bar, line, or pie) and returns it as a Base64-encoded string.
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
data (dict): A dictionary where keys are labels and values are numerical data.
|
| 12 |
+
labels (list): The labels for the data points.
|
| 13 |
+
plot_type (str): The type of plot to generate ('bar', 'line', or 'pie').
|
| 14 |
+
title (str): The title of the plot.
|
| 15 |
+
x_label (str): The label for the x-axis.
|
| 16 |
+
y_label (str): The label for the y-axis.
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
str: A Base64-encoded string of the plot image.
|
| 20 |
+
"""
|
| 21 |
+
fig, ax = plt.subplots()
|
| 22 |
+
|
| 23 |
+
# Extract keys and values from the data dictionary
|
| 24 |
+
x_data = list(data.keys())
|
| 25 |
+
y_data = list(data.values())
|
| 26 |
+
|
| 27 |
+
if plot_type == 'bar':
|
| 28 |
+
ax.bar(x_data, y_data, tick_label=labels)
|
| 29 |
+
elif plot_type == 'line':
|
| 30 |
+
ax.plot(x_data, y_data)
|
| 31 |
+
elif plot_type == 'pie':
|
| 32 |
+
ax.pie(y_data, labels=x_data, autopct='%1.1f%%', startangle=90)
|
| 33 |
+
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
|
| 34 |
+
else:
|
| 35 |
+
raise ValueError("Invalid plot_type. Choose 'bar', 'line', or 'pie'.")
|
| 36 |
+
|
| 37 |
+
ax.set_title(title)
|
| 38 |
+
ax.set_xlabel(x_label)
|
| 39 |
+
ax.set_ylabel(y_label)
|
| 40 |
+
|
| 41 |
+
# Save plot to a BytesIO buffer in memory instead of to a file
|
| 42 |
+
buf = BytesIO()
|
| 43 |
+
plt.savefig(buf, format='png', bbox_inches='tight')
|
| 44 |
+
plt.close(fig) # Close the plot to free up memory
|
| 45 |
+
|
| 46 |
+
# Encode the image data to a Base64 string
|
| 47 |
+
img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
|
| 48 |
+
return f'<img src="data:image/png;base64,{img_base64}"/>'
|