|
| 1 | +from typing import Any, Type |
| 2 | +import pandas as pd |
| 3 | +from vuecore import EngineType, PlotType |
| 4 | +from vuecore.engines import get_builder, get_saver |
| 5 | +from pydantic import BaseModel |
| 6 | + |
| 7 | + |
| 8 | +def create_plot( |
| 9 | + data: pd.DataFrame, |
| 10 | + config: Type[BaseModel], |
| 11 | + plot_type: PlotType, |
| 12 | + engine: EngineType = EngineType.PLOTLY, |
| 13 | + file_path: str = None, |
| 14 | + **kwargs, |
| 15 | +) -> Any: |
| 16 | + """ |
| 17 | + Factory function to create, style, and optionally save plots. |
| 18 | +
|
| 19 | + This function handles the common workflow for creating plots: |
| 20 | + 1. Validate configuration using the provided Pydantic model |
| 21 | + 2. Get the appropriate builder function from the engine registry |
| 22 | + 3. Build the figure using the builder |
| 23 | + 4. Optionally save the plot if a file path is provided |
| 24 | +
|
| 25 | + Parameters |
| 26 | + ---------- |
| 27 | + data : pd.DataFrame |
| 28 | + The DataFrame containing the data to be plotted. |
| 29 | + config : Type[BaseModel] |
| 30 | + The Pydantic config class for validation. |
| 31 | + plot_type : PlotType |
| 32 | + The plot type from the `PlotType` enum (e.g., PlotType.BAR, PlotType.BOX, etc). |
| 33 | + engine : EngineType, optional |
| 34 | + The plotting engine to use for rendering the plot. |
| 35 | + Defaults to `EngineType.PLOTLY`. |
| 36 | + file_path : str, optional |
| 37 | + If provided, the path where the final plot will be saved. |
| 38 | + **kwargs |
| 39 | + Keyword arguments for plot configuration. |
| 40 | +
|
| 41 | + Returns |
| 42 | + ------- |
| 43 | + Any |
| 44 | + The final plot object returned by the selected engine. |
| 45 | + """ |
| 46 | + # 1. Validate configuration using Pydantic |
| 47 | + config = config(**kwargs) |
| 48 | + |
| 49 | + # 2. Get the correct builder function from the registry |
| 50 | + builder_func = get_builder(plot_type=plot_type, engine=engine) |
| 51 | + |
| 52 | + # 3. Build the figure object |
| 53 | + figure = builder_func(data, config) |
| 54 | + |
| 55 | + # 4. Save the plot using the correct saver function, if a file_path is provided |
| 56 | + if file_path: |
| 57 | + saver_func = get_saver(engine=engine) |
| 58 | + saver_func(figure, file_path) |
| 59 | + |
| 60 | + return figure |
0 commit comments