Spaces:
Paused
Paused
File size: 8,169 Bytes
342973b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
"""
Chart Generator - Generate charts and graphs
"""
import io
from typing import Dict, List, Optional
import logging
logger = logging.getLogger(__name__)
class ChartGenerator:
"""
Generate various types of charts and graphs.
"""
def __init__(self):
"""Initialize chart generator."""
self.chart_types = ["bar", "line", "pie", "scatter", "histogram"]
def generate_bar_chart(
self,
labels: List[str],
values: List[float],
title: str = "Bar Chart",
xlabel: str = "Categories",
ylabel: str = "Values",
) -> bytes:
"""
Generate bar chart.
Args:
labels: Category labels
values: Category values
title: Chart title
xlabel: X-axis label
ylabel: Y-axis label
Returns:
Chart image bytes
"""
try:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.bar(labels, values, color="steelblue")
plt.title(title, fontsize=16, fontweight="bold")
plt.xlabel(xlabel, fontsize=12)
plt.ylabel(ylabel, fontsize=12)
plt.xticks(rotation=45, ha="right")
plt.tight_layout()
# Save to bytes
buffer = io.BytesIO()
plt.savefig(buffer, format="png", dpi=300)
buffer.seek(0)
plt.close()
return buffer.getvalue()
except ImportError:
logger.warning("matplotlib not available")
return b"Chart generation failed"
def generate_line_chart(
self,
x_data: List[float],
y_data: List[float],
title: str = "Line Chart",
xlabel: str = "X",
ylabel: str = "Y",
) -> bytes:
"""
Generate line chart.
Args:
x_data: X-axis data
y_data: Y-axis data
title: Chart title
xlabel: X-axis label
ylabel: Y-axis label
Returns:
Chart image bytes
"""
try:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.plot(x_data, y_data, marker="o", linestyle="-", color="steelblue", linewidth=2)
plt.title(title, fontsize=16, fontweight="bold")
plt.xlabel(xlabel, fontsize=12)
plt.ylabel(ylabel, fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
# Save to bytes
buffer = io.BytesIO()
plt.savefig(buffer, format="png", dpi=300)
buffer.seek(0)
plt.close()
return buffer.getvalue()
except ImportError:
logger.warning("matplotlib not available")
return b"Chart generation failed"
def generate_pie_chart(
self, labels: List[str], values: List[float], title: str = "Pie Chart"
) -> bytes:
"""
Generate pie chart.
Args:
labels: Slice labels
values: Slice values
title: Chart title
Returns:
Chart image bytes
"""
try:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.pie(values, labels=labels, autopct="%1.1f%%", startangle=90)
plt.title(title, fontsize=16, fontweight="bold")
plt.axis("equal")
plt.tight_layout()
# Save to bytes
buffer = io.BytesIO()
plt.savefig(buffer, format="png", dpi=300)
buffer.seek(0)
plt.close()
return buffer.getvalue()
except ImportError:
logger.warning("matplotlib not available")
return b"Chart generation failed"
def generate_scatter_plot(
self,
x_data: List[float],
y_data: List[float],
title: str = "Scatter Plot",
xlabel: str = "X",
ylabel: str = "Y",
) -> bytes:
"""
Generate scatter plot.
Args:
x_data: X-axis data
y_data: Y-axis data
title: Chart title
xlabel: X-axis label
ylabel: Y-axis label
Returns:
Chart image bytes
"""
try:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.scatter(x_data, y_data, color="steelblue", s=100, alpha=0.6)
plt.title(title, fontsize=16, fontweight="bold")
plt.xlabel(xlabel, fontsize=12)
plt.ylabel(ylabel, fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
# Save to bytes
buffer = io.BytesIO()
plt.savefig(buffer, format="png", dpi=300)
buffer.seek(0)
plt.close()
return buffer.getvalue()
except ImportError:
logger.warning("matplotlib not available")
return b"Chart generation failed"
def generate_histogram(
self, data: List[float], title: str = "Histogram", xlabel: str = "Values", bins: int = 10
) -> bytes:
"""
Generate histogram.
Args:
data: Data values
title: Chart title
xlabel: X-axis label
bins: Number of bins
Returns:
Chart image bytes
"""
try:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.hist(data, bins=bins, color="steelblue", edgecolor="black")
plt.title(title, fontsize=16, fontweight="bold")
plt.xlabel(xlabel, fontsize=12)
plt.ylabel("Frequency", fontsize=12)
plt.grid(True, alpha=0.3, axis="y")
plt.tight_layout()
# Save to bytes
buffer = io.BytesIO()
plt.savefig(buffer, format="png", dpi=300)
buffer.seek(0)
plt.close()
return buffer.getvalue()
except ImportError:
logger.warning("matplotlib not available")
return b"Chart generation failed"
def generate_multi_line_chart(
self,
data: Dict[str, List[float]],
x_labels: List[str] = None,
title: str = "Multi-Line Chart",
xlabel: str = "X",
ylabel: str = "Y",
) -> bytes:
"""
Generate multi-line chart.
Args:
data: Dictionary of {series_name: values_list}
x_labels: X-axis labels
title: Chart title
xlabel: X-axis label
ylabel: Y-axis label
Returns:
Chart image bytes
"""
try:
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
for series_name, values in data.items():
if x_labels:
plt.plot(x_labels, values, marker="o", label=series_name, linewidth=2)
else:
plt.plot(values, marker="o", label=series_name, linewidth=2)
plt.title(title, fontsize=16, fontweight="bold")
plt.xlabel(xlabel, fontsize=12)
plt.ylabel(ylabel, fontsize=12)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
# Save to bytes
buffer = io.BytesIO()
plt.savefig(buffer, format="png", dpi=300)
buffer.seek(0)
plt.close()
return buffer.getvalue()
except ImportError:
logger.warning("matplotlib not available")
return b"Chart generation failed"
def generate_chart_html_embed(self, chart_bytes: bytes, alt_text: str = "Chart") -> str:
"""
Generate HTML embed code for chart.
Args:
chart_bytes: Chart image bytes
alt_text: Alternative text for image
Returns:
HTML embed code
"""
import base64
encoded = base64.b64encode(chart_bytes).decode("utf-8")
return f'<img src="data:image/png;base64,{encoded}" alt="{alt_text}" style="max-width: 100%;">'
|