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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
| import pandas as pd import numpy as np from typing import Dict, List, Any import plotly.graph_objects as go import plotly.express as px from plotly.subplots import make_subplots import json
class ChartGenerator: """图表生成器""" def __init__(self): self.chart_types = { 'line': self._generate_line_chart, 'bar': self._generate_bar_chart, 'scatter': self._generate_scatter_chart, 'pie': self._generate_pie_chart, 'heatmap': self._generate_heatmap, 'histogram': self._generate_histogram, 'box': self._generate_box_chart, 'area': self._generate_area_chart, 'treemap': self._generate_treemap, 'sunburst': self._generate_sunburst } def generate_chart_data(self, df: pd.DataFrame, chart_type: str, config: Dict[str, Any]) -> Dict[str, Any]: """生成图表数据""" if chart_type not in self.chart_types: raise ValueError(f"Unsupported chart type: {chart_type}") return self.chart_types[chart_type](df, config) def _generate_line_chart(self, df: pd.DataFrame, config: Dict[str, Any]) -> Dict[str, Any]: """生成折线图""" x_col = config.get('x_column') y_cols = config.get('y_columns', []) if not x_col or not y_cols: raise ValueError("x_column and y_columns are required for line chart") chart_data = { 'type': 'line', 'data': { 'labels': df[x_col].tolist(), 'datasets': [] }, 'options': { 'responsive': True, 'plugins': { 'title': { 'display': True, 'text': config.get('title', 'Line Chart') }, 'legend': { 'display': len(y_cols) > 1 } }, 'scales': { 'x': { 'display': True, 'title': { 'display': True, 'text': config.get('x_label', x_col) } }, 'y': { 'display': True, 'title': { 'display': True, 'text': config.get('y_label', 'Value') } } } } } colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'] for i, y_col in enumerate(y_cols): dataset = { 'label': y_col, 'data': df[y_col].tolist(), 'borderColor': colors[i % len(colors)], 'backgroundColor': colors[i % len(colors)] + '20', 'fill': config.get('fill', False), 'tension': config.get('tension', 0.1) } chart_data['data']['datasets'].append(dataset) return chart_data def _generate_bar_chart(self, df: pd.DataFrame, config: Dict[str, Any]) -> Dict[str, Any]: """生成柱状图""" x_col = config.get('x_column') y_col = config.get('y_column') if not x_col or not y_col: raise ValueError("x_column and y_column are required for bar chart") if config.get('aggregate', False): agg_func = config.get('agg_function', 'sum') df_agg = df.groupby(x_col)[y_col].agg(agg_func).reset_index() else: df_agg = df[[x_col, y_col]].copy() chart_data = { 'type': 'bar', 'data': { 'labels': df_agg[x_col].tolist(), 'datasets': [{ 'label': config.get('label', y_col), 'data': df_agg[y_col].tolist(), 'backgroundColor': config.get('color', '#36A2EB'), 'borderColor': config.get('border_color', '#36A2EB'), 'borderWidth': 1 }] }, 'options': { 'responsive': True, 'plugins': { 'title': { 'display': True, 'text': config.get('title', 'Bar Chart') } }, 'scales': { 'x': { 'title': { 'display': True, 'text': config.get('x_label', x_col) } }, 'y': { 'title': { 'display': True, 'text': config.get('y_label', y_col) } } } } } return chart_data def _generate_scatter_chart(self, df: pd.DataFrame, config: Dict[str, Any]) -> Dict[str, Any]: """生成散点图""" x_col = config.get('x_column') y_col = config.get('y_column') size_col = config.get('size_column') color_col = config.get('color_column') if not x_col or not y_col: raise ValueError("x_column and y_column are required for scatter chart") data_points = [] for _, row in df.iterrows(): point = { 'x': row[x_col], 'y': row[y_col] } if size_col: point['r'] = row[size_col] / df[size_col].max() * 20 data_points.append(point) chart_data = { 'type': 'scatter', 'data': { 'datasets': [{ 'label': config.get('label', 'Data Points'), 'data': data_points, 'backgroundColor': config.get('color', '#FF6384'), 'borderColor': config.get('border_color', '#FF6384') }] }, 'options': { 'responsive': True, 'plugins': { 'title': { 'display': True, 'text': config.get('title', 'Scatter Plot') } }, 'scales': { 'x': { 'type': 'linear', 'position': 'bottom', 'title': { 'display': True, 'text': config.get('x_label', x_col) } }, 'y': { 'title': { 'display': True, 'text': config.get('y_label', y_col) } } } } } return chart_data def _generate_pie_chart(self, df: pd.DataFrame, config: Dict[str, Any]) -> Dict[str, Any]: """生成饼图""" label_col = config.get('label_column') value_col = config.get('value_column') if not label_col or not value_col: raise ValueError("label_column and value_column are required for pie chart") df_agg = df.groupby(label_col)[value_col].sum().reset_index() colors = [ '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF', '#4BC0C0', '#FF6384' ] chart_data = { 'type': 'pie', 'data': { 'labels': df_agg[label_col].tolist(), 'datasets': [{ 'data': df_agg[value_col].tolist(), 'backgroundColor': colors[:len(df_agg)], 'borderWidth': 2, 'borderColor': '#fff' }] }, 'options': { 'responsive': True, 'plugins': { 'title': { 'display': True, 'text': config.get('title', 'Pie Chart') }, 'legend': { 'position': config.get('legend_position', 'right') } } } } return chart_data def _generate_heatmap(self, df: pd.DataFrame, config: Dict[str, Any]) -> Dict[str, Any]: """生成热力图""" x_col = config.get('x_column') y_col = config.get('y_column') value_col = config.get('value_column') if not all([x_col, y_col, value_col]): raise ValueError("x_column, y_column, and value_column are required for heatmap") pivot_table = df.pivot_table( values=value_col, index=y_col, columns=x_col, aggfunc='mean', fill_value=0 ) heatmap_data = [] for i, y_val in enumerate(pivot_table.index): for j, x_val in enumerate(pivot_table.columns): heatmap_data.append({ 'x': j, 'y': i, 'v': pivot_table.iloc[i, j] }) chart_data = { 'type': 'heatmap', 'data': { 'datasets': [{ 'label': config.get('label', 'Heatmap'), 'data': heatmap_data, 'backgroundColor': function(ctx) { return 'rgba(255, 99, 132, 0.2)' } }] }, 'options': { 'responsive': True, 'plugins': { 'title': { 'display': True, 'text': config.get('title', 'Heatmap') } }, 'scales': { 'x': { 'type': 'linear', 'position': 'bottom', 'min': 0, 'max': len(pivot_table.columns) - 1, 'ticks': { 'callback': function(value, index, values) { return pivot_table.columns[value] if value < len(pivot_table.columns) else '' } } }, 'y': { 'type': 'linear', 'min': 0, 'max': len(pivot_table.index) - 1, 'ticks': { 'callback': function(value, index, values) { return pivot_table.index[value] if value < len(pivot_table.index) else '' } } } } }, 'pivot_data': { 'x_labels': pivot_table.columns.tolist(), 'y_labels': pivot_table.index.tolist(), 'values': pivot_table.values.tolist() } } return chart_data def _generate_histogram(self, df: pd.DataFrame, config: Dict[str, Any]) -> Dict[str, Any]: """生成直方图""" column = config.get('column') bins = config.get('bins', 20) if not column: raise ValueError("column is required for histogram") hist, bin_edges = np.histogram(df[column].dropna(), bins=bins) labels = [(bin_edges[i] + bin_edges[i+1]) / 2 for i in range(len(bin_edges)-1)] chart_data = { 'type': 'bar', 'data': { 'labels': [f'{bin_edges[i]:.2f}-{bin_edges[i+1]:.2f}' for i in range(len(bin_edges)-1)], 'datasets': [{ 'label': config.get('label', f'Frequency of {column}'), 'data': hist.tolist(), 'backgroundColor': config.get('color', '#36A2EB'), 'borderColor': config.get('border_color', '#36A2EB'), 'borderWidth': 1 }] }, 'options': { 'responsive': True, 'plugins': { 'title': { 'display': True, 'text': config.get('title', f'Histogram of {column}') } }, 'scales': { 'x': { 'title': { 'display': True, 'text': config.get('x_label', column) } }, 'y': { 'title': { 'display': True, 'text': 'Frequency' } } } } } return chart_data def generate_dashboard_layout(self, widgets: List[Dict[str, Any]]) -> Dict[str, Any]: """生成仪表板布局""" layout = { 'widgets': [], 'layout': { 'rows': [], 'columns': 12 } } current_row = [] current_width = 0 for widget in widgets: widget_width = widget.get('width', 6) if current_width + widget_width > 12: if current_row: layout['layout']['rows'].append(current_row) current_row = [widget] current_width = widget_width else: current_row.append(widget) current_width += widget_width if current_row: layout['layout']['rows'].append(current_row) layout['widgets'] = widgets return layout
|