feat: add area-basic implementation (9 libraries)#508
Conversation
## Summary Implements `area-basic` for **seaborn** library. **Parent Issue:** #201 **Sub-Issue:** #210 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/seaborn/fill_between/area-basic/default.py` ## Changes - Rewrites implementation to follow KISS style guidelines (no functions/classes) - Uses example data from spec (monthly sales) - Uses palette colors from default-style-guide.md (#306998 Python Blue) - Proper font sizes (20pt for labels/title, 16pt for ticks) - Seaborn styling with matplotlib fill_between (seaborn has no native area chart) ## Notes Seaborn does not have a native area chart function. This implementation uses `matplotlib.pyplot.fill_between()` with seaborn's styling for a consistent look. Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **matplotlib** library. **Parent Issue:** #201 **Sub-Issue:** #209 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/matplotlib/fill_between/area-basic/default.py` ## Details - Uses `ax.fill_between()` for the filled area with semi-transparent Python Blue color (#306998) - Includes solid line on top for better edge visibility - Monthly sales data from the spec with proper categorical x-axis labels - Y-axis starts at 0 for proper area representation - Follows KISS style: simple sequential script without functions - Font sizes and styling per default-style-guide.md Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **pygal** library. **Parent Issue:** #201 **Sub-Issue:** #229 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/pygal/line/area-basic/default.py` ## Changes - Rewrote implementation to follow KISS style guidelines (no functions, sequential code) - Uses 4800x2700 dimensions per style guide - Applied Python Blue color (#306998) from the style palette - Configured proper font sizes for high-resolution output - Uses the spec example data (monthly sales) ## Visual Quality - Title: Present and clear - Axis Labels: Both X and Y axes properly labeled - Legend: Present at bottom - Fill: Area properly filled with transparency - Dimensions: 4800x2700 px (16:9 aspect ratio) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **plotnine** library. **Parent Issue:** #201 **Sub-Issue:** #224 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/plotnine/area/area-basic/default.py` ## Changes - Simplified to KISS style (no functions, classes, or type hints) - Uses spec example data (monthly sales) - Python Blue color palette (#306998) - Output: 4800x2700px at 300dpi Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **letsplot** library. **Parent Issue:** #201 **Sub-Issue:** #240 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/letsplot/area/area-basic/default.py` ## Details - Uses `geom_area()` with Python Blue (#306998) fill color - Implements proper month labeling via `scale_x_continuous()` with custom breaks and labels - Follows the 4800 × 2700 px image size requirement (using ggsize 1600x900 with scale=3) - Uses `theme_minimal()` with customized font sizes for readability Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **plotly** library. **Parent Issue:** #201 **Sub-Issue:** #211 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/plotly/scatter/area-basic/default.py` ## Changes - Simple KISS-style implementation using `go.Scatter` with `fill='tozeroy'` - Uses Python Blue (#306998) from the default style guide - Outputs 4800x2700px image (1600x900 @ scale 3) - Clean layout with axis labels, title, and subtle grid Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **highcharts** library. **Parent Issue:** #201 **Sub-Issue:** #234 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/highcharts/area/area-basic/default.py` ## Features - Basic area chart with filled region between line and x-axis - Supports both numeric and categorical x-axis values - Configurable fill opacity and line width - Grid lines with subtle styling (dotted, low opacity) - Proper axis labels and title - Data markers on data points - PNG export via Selenium screenshot Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **altair** library. **Parent Issue:** #201 **Sub-Issue:** #219 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/altair/area/area-basic/default.py` ## Details - Uses `mark_area()` with 0.5 opacity and Python Blue color (#306998) - Overlays `mark_line()` for visible line on top of area - Configures axis with subtle grid (opacity 0.3) - 1600x900 base size with 3x scale factor for 4800x2700 output - Font sizes: title 20pt, axis labels 20pt, tick labels 16pt Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **highcharts** library. **Parent Issue:** #201 **Sub-Issue:** #339 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/highcharts/area/area-basic/default.py` ## Changes - Simple sequential script following KISS principle (no functions, classes, or type hints) - Uses Python Blue (#306998) as primary color per style guide - 4800x2700 px output per style guide - Inline Highcharts JS for reliable headless Chrome rendering - Proper `container="container"` specification for chart rendering - Subtle grid with 10% opacity - Appropriate font sizes for the large canvas (48px title, 40px axis titles, 32px labels) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **pygal** library. **Parent Issue:** #201 **Sub-Issue:** #337 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/pygal/area/area-basic/default.py` ## Details - Uses `pygal.Line` with `fill=True` to create area chart effect - Custom style with project color palette (#306998 Python Blue) - Output: 4800×2700 px PNG (per style guide) - Configured with: - Appropriate font sizes for high-res output (title: 60pt, labels: 48pt) - Subtle y-axis grid - Transparency (opacity=0.5) for the fill - Line stroke width 4px with visible dot markers Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **highcharts** library. **Parent Issue:** #201 **Sub-Issue:** #396 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/highcharts/area/area-basic/default.py` ## Details - Uses AreaSeries with fill opacity of 0.5 for appropriate transparency - Line width of 4px for visibility on top of filled area - Font sizes scaled appropriately for 4800x2700px output - Python Blue (#306998) color from style guide - Monthly sales data as sample data - Inline Highcharts JS for headless Chrome compatibility Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **letsplot** library. **Parent Issue:** #201 **Sub-Issue:** #341 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/letsplot/area/area-basic/default.py` ## Changes - Added separate `geom_line` layer for visible line on top of filled area - Uses alpha=0.5 for the area fill as per spec requirements - Line width of 2 matches style guide recommendations - Uses Python Blue (#306998) from the color palette - Output size: 4800 × 2700 px (1600 × 900 base with scale=3) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **altair** library. **Parent Issue:** #201 **Sub-Issue:** #395 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/altair/area/area-basic/default.py` ## Changes - Uses `mark_area()` with inline `line` parameter for cleaner code - Extended data from 6 to 12 months for richer visualization - Added `configure_view(strokeWidth=0)` to remove chart border - Configured proper font sizes for title, axis labels, and tick labels - Subtle grid with `gridOpacity=0.3` - Outputs 4800×2700px PNG (1600×900 × scale_factor=3.0) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **plotly** library. **Parent Issue:** #201 **Sub-Issue:** #328 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/plotly/scatter/area-basic/default.py` ## Details - Uses `go.Scatter` with `fill="tozeroy"` for area visualization - Monthly sales data as example dataset - Fill color: rgba(48, 105, 152, 0.5) - Python Blue with 50% transparency - Line color: #306998 (Python Blue) with width 2 - Proper axis labels and centered title - Output size: 4800×2700 px (1600×900 with scale=3) - Subtle grid with alpha 0.1 - Uses plotly_white template for clean appearance Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **highcharts** library. **Parent Issue:** #201 **Sub-Issue:** #428 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/highcharts/area/area-basic/default.py` ## Features - Basic area chart with monthly sales data - Python Blue (#306998) color scheme following style guide - 4800x2700 px output size - Proper axis labels with readable font sizes - Subtle grid (0.1 opacity) - Markers on data points - 50% fill opacity for area Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
## Summary Implements `area-basic` for **bokeh** library. **Parent Issue:** #201 **Sub-Issue:** #215 **Base Branch:** `plot/area-basic` **Attempt:** 2/3 ## Implementation - `plots/bokeh/varea/area-basic/default.py` ## Details - Uses `varea` method for filled area chart - Includes `line` overlay for clearer boundary - Monthly sales data from the spec (Jan-Dec) - Categorical x-axis with month label overrides - Python Blue (#306998) color with 70% opacity fill - 4800x2700px output per style guide - Font sizes: 20pt for title/axis labels, 16pt for tick labels - Subtle grid with 0.3 alpha ## Dependencies Added `selenium>=4.15.0` and `webdriver-manager>=4.0.0` to `lib-bokeh` optional dependency in `pyproject.toml`. This is required for bokeh's `export_png()` function. ##⚠️ CI Fix Required (Workflow Permission) The CI workflow needs Chrome setup for bokeh tests (similar to highcharts). A maintainer needs to update `.github/workflows/ci-plottest.yml`: **Change line 69-71 from:** ```yaml - name: Setup Chrome for Highcharts if: steps.detect_libs.outputs.has_plots == 'true' && contains(steps.detect_libs.outputs.libraries, 'highcharts') ``` **To:** ```yaml - name: Setup Chrome for Bokeh/Highcharts if: steps.detect_libs.outputs.has_plots == 'true' && (contains(steps.detect_libs.outputs.libraries, 'highcharts') || contains(steps.detect_libs.outputs.libraries, 'bokeh')) ``` This cannot be pushed from this workflow due to GitHub App workflow permissions. ## Local Test Result The implementation runs successfully locally with Chrome and produces a valid 4800x2700 PNG. --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Markus Neusinger <2921697+MarkusNeusinger@users.noreply.github.com>
## Summary Implements `area-basic` for **pygal** library. **Parent Issue:** #201 **Sub-Issue:** #427 **Base Branch:** `plot/area-basic` **Attempt:** 4/3 ## Implementation - `plots/pygal/area/area-basic/default.py` ## Features - Creates a filled area chart using pygal's Line chart with `fill=True` - Uses PyPlots color palette (#306998 - Python Blue) - 4800x2700 pixel output (16:9 aspect ratio) - Custom style with appropriate font sizes for readability - Clean axes labels (Month, Sales ($)) - Subtle grid on Y-axis ## Fix for CI Issue Previous attempts failed because: 1. The base branch has a duplicate file at `plots/pygal/line/area-basic/default.py` 2. Deleting this duplicate caused CI to try to test the deleted file (which doesn't exist) This attempt keeps only the correct `area/` implementation in the diff without touching the `line/` duplicate. The duplicate should be cleaned up separately. Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Markus Neusinger <2921697+MarkusNeusinger@users.noreply.github.com>
## Summary Implements `area-basic` for **highcharts** library. **Parent Issue:** #201 **Sub-Issue:** #473 **Base Branch:** `plot/area-basic` **Attempt:** 1/3 ## Implementation - `plots/highcharts/area/area-basic/default.py` ## Features - Basic area chart showing monthly sales trend - Python Blue (#306998) color scheme - Filled area with 50% opacity - Visible markers on data points - Subtle grid lines (10% opacity) - Full x-axis labels (Jan-Dec) and y-axis label (Sales $) - 4800x2700px output via Selenium screenshot Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
This PR attempts to add area-basic plot implementations across all 9 supported libraries. However, all implementations have a critical architectural issue: they use hardcoded data in the main module body instead of following the project's established pattern of providing a reusable create_plot() function with proper type hints, docstrings, and validation.
Critical Issues:
- All 10 implementation files lack the required
create_plot(data, x, y, **params)function - Implementations have hardcoded data in the main body, preventing programmatic use via the API
- Missing input validation, type hints, and comprehensive docstrings
- No
if __name__ == "__main__":guard for example code
Impact:
- These implementations cannot be used programmatically through the pyplots API
- They deviate from 100% of existing implementations in the repository (all other plots follow the function-based pattern)
- The spec file correctly shows
create_plot()usage in examples (lines 50, 55), but implementations don't provide this function
Reviewed changes
Copilot reviewed 11 out of 12 changed files in this pull request and generated 10 comments.
Show a summary per file
| File | Description |
|---|---|
| specs/area-basic.md | Updated spec with comprehensive requirements, parameters, and examples - looks good and follows expected format |
| plots/seaborn/fill_between/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/pygal/line/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/pygal/area/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/plotnine/area/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/plotly/scatter/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/matplotlib/fill_between/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/letsplot/area/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/highcharts/area/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/bokeh/varea/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| plots/altair/area/area-basic/default.py | Missing create_plot() function; has hardcoded data instead |
| """ | ||
| area-basic: Basic Area Chart | ||
| Implementation for: matplotlib | ||
| Variant: default | ||
| Python: 3.10+ | ||
| Library: matplotlib | ||
| """ | ||
|
|
||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| import matplotlib.pyplot as plt | ||
| import pandas as pd | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from matplotlib.figure import Figure | ||
|
|
||
|
|
||
| def create_plot( | ||
| data: pd.DataFrame, | ||
| x: str, | ||
| y: str, | ||
| color: str = "steelblue", | ||
| alpha: float = 0.4, | ||
| line_color: Optional[str] = None, | ||
| line_width: float = 2.0, | ||
| title: Optional[str] = None, | ||
| xlabel: Optional[str] = None, | ||
| ylabel: Optional[str] = None, | ||
| figsize: tuple[float, float] = (16, 9), | ||
| **kwargs, | ||
| ) -> "Figure": | ||
| """ | ||
| Create a basic area chart showing a filled region between the x-axis and a line. | ||
|
|
||
| Args: | ||
| data: Input DataFrame with required columns | ||
| x: Column name for x-axis values (continuous sequence) | ||
| y: Column name for y-axis values (numeric values) | ||
| color: Fill color for the area (default: "steelblue") | ||
| alpha: Transparency level for the filled area 0.0-1.0 (default: 0.4) | ||
| line_color: Color of the top edge line (default: same as fill color) | ||
| line_width: Width of the top edge line (default: 2.0) | ||
| title: Plot title (default: None) | ||
| xlabel: Custom x-axis label (default: column name) | ||
| ylabel: Custom y-axis label (default: column name) | ||
| figsize: Figure size as (width, height) (default: (16, 9)) | ||
| **kwargs: Additional parameters passed to ax.fill_between() | ||
|
|
||
| Returns: | ||
| Matplotlib Figure object | ||
|
|
||
| Raises: | ||
| ValueError: If data is empty | ||
| KeyError: If required columns not found | ||
|
|
||
| Example: | ||
| >>> data = pd.DataFrame({'Time': [1, 2, 3, 4, 5], 'Value': [10, 25, 15, 30, 20]}) | ||
| >>> fig = create_plot(data, x='Time', y='Value') | ||
| """ | ||
| # Input validation | ||
| if data.empty: | ||
| raise ValueError("Data cannot be empty") | ||
|
|
||
| # Check required columns | ||
| for col in [x, y]: | ||
| if col not in data.columns: | ||
| available = ", ".join(data.columns) | ||
| raise KeyError(f"Column '{col}' not found. Available: {available}") | ||
|
|
||
| # Create figure | ||
| fig, ax = plt.subplots(figsize=figsize) | ||
|
|
||
| # Get data values | ||
| x_values = data[x] | ||
| y_values = data[y] | ||
|
|
||
| # Determine line color (default to fill color if not specified) | ||
| edge_color = line_color if line_color else color | ||
|
|
||
| # Plot the filled area | ||
| ax.fill_between(x_values, y_values, alpha=alpha, color=color, **kwargs) | ||
|
|
||
| # Plot the top edge line for clarity | ||
| ax.plot(x_values, y_values, color=edge_color, linewidth=line_width) | ||
|
|
||
| # Apply styling | ||
| ax.set_xlabel(xlabel or x) | ||
| ax.set_ylabel(ylabel or y) | ||
| ax.grid(True, alpha=0.3, linestyle="--") | ||
|
|
||
| # Title | ||
| if title: | ||
| ax.set_title(title, fontsize=14, fontweight="bold") | ||
|
|
||
| # Tight layout to avoid label clipping | ||
| plt.tight_layout() | ||
|
|
||
| return fig | ||
| # Data - Monthly sales from spec | ||
| data = pd.DataFrame( | ||
| { | ||
| "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "sales": [120, 135, 148, 162, 175, 195, 210, 198, 185, 170, 158, 190], | ||
| } | ||
| ) | ||
|
|
||
| # Create plot | ||
| fig, ax = plt.subplots(figsize=(16, 9)) | ||
|
|
||
| if __name__ == "__main__": | ||
| # Sample data for testing - simulating monthly website traffic | ||
| data = pd.DataFrame( | ||
| { | ||
| "Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "Visitors": [12000, 15000, 18000, 22000, 25000, 28000, 32000, 30000, 27000, 24000, 20000, 18000], | ||
| } | ||
| ) | ||
| # Plot area chart - use numeric x-axis for proper fill_between | ||
| x = range(len(data)) | ||
| ax.fill_between(x, data["sales"], alpha=0.5, color="#306998") | ||
| ax.plot(x, data["sales"], color="#306998", linewidth=2) | ||
|
|
||
| # For a proper area chart, we need numeric x values | ||
| # Convert month names to numeric positions for continuous x-axis | ||
| data["Month_Num"] = range(1, 13) | ||
| # Set x-tick labels to month names | ||
| ax.set_xticks(x) | ||
| ax.set_xticklabels(data["month"]) | ||
|
|
||
| # Create plot | ||
| fig = create_plot( | ||
| data, x="Month_Num", y="Visitors", title="Monthly Website Traffic", xlabel="Month", ylabel="Number of Visitors" | ||
| ) | ||
| # Labels and styling | ||
| ax.set_xlabel("Month", fontsize=20) | ||
| ax.set_ylabel("Sales", fontsize=20) | ||
| ax.set_title("Monthly Sales Volume", fontsize=20) | ||
| ax.tick_params(axis="both", labelsize=16) | ||
| ax.grid(True, alpha=0.3, linestyle="--") | ||
|
|
||
| # Customize x-ticks to show month names | ||
| ax = fig.axes[0] | ||
| ax.set_xticks(range(1, 13)) | ||
| ax.set_xticklabels(data["Month"]) | ||
| # Set y-axis to start from 0 for proper area representation | ||
| ax.set_ylim(bottom=0) | ||
|
|
||
| # Save for inspection | ||
| plt.savefig("plot.png", dpi=300, bbox_inches="tight") | ||
| print("Plot saved to plot.png") | ||
| plt.tight_layout() | ||
| plt.savefig("plot.png", dpi=300, bbox_inches="tight") |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (matplotlib Figure in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/matplotlib/plot/line-basic/default.py.
| """ | ||
| area-basic: Basic Area Chart | ||
| Library: letsplot | ||
| """ | ||
|
|
||
| import pandas as pd | ||
| from lets_plot import ( | ||
| LetsPlot, | ||
| aes, | ||
| element_text, | ||
| geom_area, | ||
| geom_line, | ||
| ggplot, | ||
| ggsave, | ||
| ggsize, | ||
| labs, | ||
| scale_x_continuous, | ||
| theme, | ||
| theme_minimal, | ||
| ) | ||
|
|
||
|
|
||
| LetsPlot.setup_html() | ||
|
|
||
| # Data | ||
| months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] | ||
| data = pd.DataFrame( | ||
| {"month_num": range(len(months)), "sales": [120, 135, 148, 162, 175, 195, 210, 198, 185, 170, 158, 190]} | ||
| ) | ||
|
|
||
| # Plot | ||
| plot = ( | ||
| ggplot(data, aes(x="month_num", y="sales")) | ||
| + geom_area(fill="#306998", alpha=0.5) | ||
| + geom_line(color="#306998", size=2) | ||
| + scale_x_continuous(breaks=list(range(len(months))), labels=months) | ||
| + labs(x="Month", y="Sales", title="Basic Area Chart") | ||
| + theme_minimal() | ||
| + theme(axis_title=element_text(size=20), axis_text=element_text(size=16), plot_title=element_text(size=20)) | ||
| + ggsize(1600, 900) | ||
| ) | ||
|
|
||
| # Save - scale 3x to get 4800 × 2700 px | ||
| ggsave(plot, "plot.png", path=".", scale=3) |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (lets-plot ggplot in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/letsplot/line/line-basic/default.py.
|
|
||
|
|
||
| # Data | ||
| data = pd.DataFrame( | ||
| { | ||
| "month": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], | ||
| "sales": [100, 150, 130, 180, 200, 220, 195, 240, 260, 230, 280, 310], | ||
| } | ||
| ) | ||
|
|
||
| # Create chart with area and line | ||
| chart = ( | ||
| alt.Chart(data) | ||
| .mark_area(opacity=0.5, color="#306998", line={"color": "#306998", "strokeWidth": 2}) | ||
| .encode( | ||
| x=alt.X("month:Q", title="Month", axis=alt.Axis(labelFontSize=16, titleFontSize=20)), | ||
| y=alt.Y("sales:Q", title="Sales", axis=alt.Axis(labelFontSize=16, titleFontSize=20)), | ||
| ) | ||
| .properties(width=1600, height=900, title=alt.TitleParams(text="Basic Area Chart", fontSize=20)) | ||
| .configure_view(strokeWidth=0) | ||
| .configure_axis(grid=True, gridOpacity=0.3) | ||
| ) | ||
|
|
||
| # Save (1600 × 900 × 3 = 4800 × 2700) | ||
| chart.save("plot.png", scale_factor=3.0) |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (altair Chart in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/altair/line/line-basic/default.py.
| # Data | |
| data = pd.DataFrame( | |
| { | |
| "month": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], | |
| "sales": [100, 150, 130, 180, 200, 220, 195, 240, 260, 230, 280, 310], | |
| } | |
| ) | |
| # Create chart with area and line | |
| chart = ( | |
| alt.Chart(data) | |
| .mark_area(opacity=0.5, color="#306998", line={"color": "#306998", "strokeWidth": 2}) | |
| .encode( | |
| x=alt.X("month:Q", title="Month", axis=alt.Axis(labelFontSize=16, titleFontSize=20)), | |
| y=alt.Y("sales:Q", title="Sales", axis=alt.Axis(labelFontSize=16, titleFontSize=20)), | |
| ) | |
| .properties(width=1600, height=900, title=alt.TitleParams(text="Basic Area Chart", fontSize=20)) | |
| .configure_view(strokeWidth=0) | |
| .configure_axis(grid=True, gridOpacity=0.3) | |
| ) | |
| # Save (1600 × 900 × 3 = 4800 × 2700) | |
| chart.save("plot.png", scale_factor=3.0) | |
| from typing import TYPE_CHECKING, Any | |
| if TYPE_CHECKING: | |
| from altair import Chart | |
| def create_plot( | |
| data: pd.DataFrame, | |
| x: str, | |
| y: str, | |
| *, | |
| width: int = 1600, | |
| height: int = 900, | |
| area_color: str = "#306998", | |
| opacity: float = 0.5, | |
| line_color: str = "#306998", | |
| line_width: int = 2, | |
| x_title: str | None = None, | |
| y_title: str | None = None, | |
| title: str = "Basic Area Chart", | |
| grid: bool = True, | |
| grid_opacity: float = 0.3, | |
| **params: Any, | |
| ) -> "alt.Chart": | |
| """ | |
| Create a basic area chart using Altair. | |
| Args: | |
| data (pd.DataFrame): Input data. | |
| x (str): Column name for x-axis (must be numeric or datetime). | |
| y (str): Column name for y-axis (must be numeric). | |
| width (int, optional): Chart width in pixels. Defaults to 1600. | |
| height (int, optional): Chart height in pixels. Defaults to 900. | |
| area_color (str, optional): Area fill color. Defaults to "#306998". | |
| opacity (float, optional): Area opacity. Defaults to 0.5. | |
| line_color (str, optional): Line color. Defaults to "#306998". | |
| line_width (int, optional): Line width. Defaults to 2. | |
| x_title (str, optional): X-axis title. Defaults to column name. | |
| y_title (str, optional): Y-axis title. Defaults to column name. | |
| title (str, optional): Chart title. Defaults to "Basic Area Chart". | |
| grid (bool, optional): Show grid. Defaults to True. | |
| grid_opacity (float, optional): Grid opacity. Defaults to 0.3. | |
| **params: Additional keyword arguments for extensibility. | |
| Returns: | |
| alt.Chart: Altair area chart object. | |
| Raises: | |
| ValueError: If data is empty, or x/y columns are missing or of wrong type. | |
| Example: | |
| >>> import pandas as pd | |
| >>> from plots.altair.area.area-basic.default import create_plot | |
| >>> df = pd.DataFrame({'month': [1,2,3], 'sales': [100, 150, 130]}) | |
| >>> chart = create_plot(df, x='month', y='sales') | |
| >>> chart.show() | |
| """ | |
| if data.empty: | |
| raise ValueError("Input data is empty.") | |
| if x not in data.columns: | |
| raise ValueError(f"Column '{x}' not found in data.") | |
| if y not in data.columns: | |
| raise ValueError(f"Column '{y}' not found in data.") | |
| # Check types | |
| if not pd.api.types.is_numeric_dtype(data[x]) and not pd.api.types.is_datetime64_any_dtype(data[x]): | |
| raise ValueError(f"Column '{x}' must be numeric or datetime.") | |
| if not pd.api.types.is_numeric_dtype(data[y]): | |
| raise ValueError(f"Column '{y}' must be numeric.") | |
| x_axis_title = x_title if x_title is not None else x.capitalize() | |
| y_axis_title = y_title if y_title is not None else y.capitalize() | |
| chart = ( | |
| alt.Chart(data) | |
| .mark_area(opacity=opacity, color=area_color, line={"color": line_color, "strokeWidth": line_width}) | |
| .encode( | |
| x=alt.X(f"{x}:Q", title=x_axis_title, axis=alt.Axis(labelFontSize=16, titleFontSize=20)), | |
| y=alt.Y(f"{y}:Q", title=y_axis_title, axis=alt.Axis(labelFontSize=16, titleFontSize=20)), | |
| ) | |
| .properties(width=width, height=height, title=alt.TitleParams(text=title, fontSize=20)) | |
| .configure_view(strokeWidth=0) | |
| .configure_axis(grid=grid, gridOpacity=grid_opacity) | |
| ) | |
| return chart | |
| if __name__ == "__main__": | |
| # Example usage | |
| data = pd.DataFrame( | |
| { | |
| "month": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], | |
| "sales": [100, 150, 130, 180, 200, 220, 195, 240, 260, 230, 280, 310], | |
| } | |
| ) | |
| chart = create_plot(data, x="month", y="sales") | |
| # Save (1600 × 900 × 3 = 4800 × 2700) | |
| chart.save("plot.png", scale_factor=3.0) |
| """ | ||
| area-basic: Basic Area Chart | ||
| Implementation for: pygal | ||
| Variant: default | ||
| Python: 3.10+ | ||
| Library: pygal | ||
| """ | ||
|
|
||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| import pandas as pd | ||
| import pygal | ||
| from pygal.style import Style | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from pygal import Line | ||
|
|
||
|
|
||
| def create_plot( | ||
| data: pd.DataFrame, | ||
| x: str, | ||
| y: str, | ||
| title: Optional[str] = None, | ||
| xlabel: Optional[str] = None, | ||
| ylabel: Optional[str] = None, | ||
| fill_alpha: float = 0.5, | ||
| color: Optional[str] = None, | ||
| show_line: bool = True, | ||
| width: int = 1600, | ||
| height: int = 900, | ||
| **kwargs, | ||
| ) -> "Line": | ||
| """ | ||
| Create a basic area chart showing a filled area under a line using pygal. | ||
|
|
||
| An area chart displays a single data series as a filled region beneath | ||
| a line, ideal for showing trends while emphasizing magnitude. | ||
|
|
||
| Args: | ||
| data: Input DataFrame with required columns | ||
| x: Column name for x-axis values (categories/labels) | ||
| y: Column name for y-axis numeric values | ||
| title: Chart title (optional) | ||
| xlabel: Custom x-axis label (optional, defaults to column name) | ||
| ylabel: Custom y-axis label (optional, defaults to column name) | ||
| fill_alpha: Transparency of the filled area (default: 0.5) | ||
| color: Color for the line and fill (optional) | ||
| show_line: Whether to show the line on top of fill (default: True) | ||
| width: Figure width in pixels (default: 1600) | ||
| height: Figure height in pixels (default: 900) | ||
| **kwargs: Additional parameters for pygal configuration | ||
|
|
||
| Returns: | ||
| pygal Line chart object configured as an area chart | ||
|
|
||
| Raises: | ||
| ValueError: If data is empty | ||
| KeyError: If required columns not found | ||
|
|
||
| Example: | ||
| >>> data = pd.DataFrame({ | ||
| ... 'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'], | ||
| ... 'Sales': [100, 150, 130, 180, 200] | ||
| ... }) | ||
| >>> chart = create_plot(data, x='Month', y='Sales') | ||
| """ | ||
| # Input validation | ||
| if data.empty: | ||
| raise ValueError("Data cannot be empty") | ||
|
|
||
| # Check required columns | ||
| for col in [x, y]: | ||
| if col not in data.columns: | ||
| available = ", ".join(data.columns) | ||
| raise KeyError(f"Column '{col}' not found. Available columns: {available}") | ||
|
|
||
| # Define colors - use provided color or default | ||
| primary_color = color or "#3498db" | ||
|
|
||
| # Create custom style with appropriate opacity for fill | ||
| custom_style = Style( | ||
| background="white", | ||
| plot_background="white", | ||
| foreground="#333", | ||
| foreground_strong="#333", | ||
| foreground_subtle="#555", | ||
| opacity=fill_alpha, | ||
| opacity_hover=min(fill_alpha + 0.2, 1.0), | ||
| colors=(primary_color,), | ||
| font_family="Arial, sans-serif", | ||
| major_guide_stroke_dasharray="3,3", | ||
| guide_stroke_dasharray="1,1", | ||
| ) | ||
|
|
||
| # Create line chart with fill enabled (makes it an area chart) | ||
| chart = pygal.Line( | ||
| title=title or "Area Chart", | ||
| x_title=xlabel or x, | ||
| y_title=ylabel or y, | ||
| width=width, | ||
| height=height, | ||
| fill=True, # This enables the area fill | ||
| show_legend=True, | ||
| style=custom_style, | ||
| show_x_guides=True, | ||
| show_y_guides=True, | ||
| dots_size=3 if show_line else 0, | ||
| stroke_style={"width": 2} if show_line else {"width": 0}, | ||
| **kwargs, | ||
| ) | ||
|
|
||
| # Set x-axis labels | ||
| x_values = data[x].tolist() | ||
| chart.x_labels = [str(val) for val in x_values] | ||
|
|
||
| # Add the data series | ||
| y_values = data[y].tolist() | ||
| series_label = ylabel or y | ||
| chart.add(series_label, y_values) | ||
|
|
||
| return chart | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # Sample data for testing - monthly website traffic | ||
| data = pd.DataFrame( | ||
| { | ||
| "Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "Visitors": [12000, 15000, 18000, 22000, 25000, 28000, 30000, 32000, 29000, 26000, 23000, 20000], | ||
| } | ||
| ) | ||
|
|
||
| # Create plot | ||
| chart = create_plot( | ||
| data, | ||
| x="Month", | ||
| y="Visitors", | ||
| title="Monthly Website Traffic", | ||
| xlabel="Month", | ||
| ylabel="Number of Visitors", | ||
| fill_alpha=0.5, | ||
| color="#2ecc71", | ||
| ) | ||
|
|
||
| # Save as PNG | ||
| chart.render_to_png("plot.png") | ||
| print("Plot saved to plot.png") | ||
| # Data - monthly sales data | ||
| months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] | ||
| sales = [120, 135, 148, 162, 175, 195, 210, 198, 185, 170, 158, 190] | ||
|
|
||
| # Custom style with PyPlots color palette | ||
| custom_style = Style( | ||
| background="white", | ||
| plot_background="white", | ||
| foreground="#333333", | ||
| foreground_strong="#333333", | ||
| foreground_subtle="#666666", | ||
| opacity=0.7, | ||
| opacity_hover=0.9, | ||
| colors=("#306998",), # Python Blue from style guide | ||
| font_family="Arial, sans-serif", | ||
| title_font_size=48, | ||
| label_font_size=36, | ||
| major_label_font_size=36, | ||
| legend_font_size=36, | ||
| ) | ||
|
|
||
| # Create area chart (Line chart with fill=True) | ||
| chart = pygal.Line( | ||
| width=4800, | ||
| height=2700, | ||
| title="Monthly Sales Performance", | ||
| x_title="Month", | ||
| y_title="Sales (Units)", | ||
| style=custom_style, | ||
| fill=True, | ||
| show_legend=True, | ||
| legend_at_bottom=True, | ||
| show_x_guides=False, | ||
| show_y_guides=True, | ||
| dots_size=6, | ||
| stroke_style={"width": 4}, | ||
| ) | ||
|
|
||
| # Set x-axis labels | ||
| chart.x_labels = months | ||
|
|
||
| # Add data series | ||
| chart.add("Sales", sales) | ||
|
|
||
| # Save as PNG | ||
| chart.render_to_png("plot.png") |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (pygal Line chart in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/pygal/line/line-basic/default.py.
| """ | ||
| area-basic: Basic Area Chart | ||
| Implementation for: plotnine | ||
| Variant: default | ||
| Python: 3.10+ | ||
| Library: plotnine | ||
| """ | ||
|
|
||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| import numpy as np | ||
| import pandas as pd | ||
| from plotnine import aes, element_line, element_text, geom_area, geom_line, ggplot, labs, theme, theme_minimal | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from plotnine import ggplot as GGPlot | ||
|
|
||
|
|
||
| def create_plot( | ||
| data: pd.DataFrame, | ||
| x: str, | ||
| y: str, | ||
| title: Optional[str] = None, | ||
| xlabel: Optional[str] = None, | ||
| ylabel: Optional[str] = None, | ||
| color: str = "steelblue", | ||
| alpha: float = 0.6, | ||
| line_color: Optional[str] = None, | ||
| line_width: float = 1.5, | ||
| width: int = 16, | ||
| height: int = 9, | ||
| **kwargs, | ||
| ) -> "GGPlot": | ||
| """ | ||
| Create a basic area chart showing values over a continuous axis using plotnine (ggplot2 syntax). | ||
|
|
||
| Args: | ||
| data: Input DataFrame with required columns | ||
| x: Column name for x-axis values (numeric or datetime) | ||
| y: Column name for y-axis values (numeric) | ||
| title: Plot title (optional) | ||
| xlabel: Custom x-axis label (optional, defaults to x column name) | ||
| ylabel: Custom y-axis label (optional, defaults to y column name) | ||
| color: Fill color for the area (default: 'steelblue') | ||
| alpha: Fill transparency level (default: 0.6) | ||
| line_color: Color of the top line (default: same as color) | ||
| line_width: Width of the top line (default: 1.5) | ||
| width: Figure width in inches (default: 16) | ||
| height: Figure height in inches (default: 9) | ||
| **kwargs: Additional parameters for geom_area | ||
|
|
||
| Returns: | ||
| plotnine ggplot object | ||
|
|
||
| Raises: | ||
| ValueError: If data is empty | ||
| KeyError: If required columns not found | ||
|
|
||
| Example: | ||
| >>> data = pd.DataFrame({ | ||
| ... 'time': [1, 2, 3, 4, 5], | ||
| ... 'value': [10, 25, 15, 30, 20] | ||
| ... }) | ||
| >>> plot = create_plot(data, x='time', y='value') | ||
| """ | ||
| # Input validation | ||
| if data.empty: | ||
| raise ValueError("Data cannot be empty") | ||
|
|
||
| # Check required columns | ||
| for col in [x, y]: | ||
| if col not in data.columns: | ||
| available = ", ".join(data.columns) | ||
| raise KeyError(f"Column '{col}' not found. Available columns: {available}") | ||
|
|
||
| # Use the same color for line if not specified | ||
| if line_color is None: | ||
| line_color = color | ||
|
|
||
| # Sort data by x to ensure proper area rendering | ||
| data_sorted = data.sort_values(by=x).copy() | ||
|
|
||
| # Create the ggplot object with area and line | ||
| plot = ( | ||
| ggplot(data_sorted, aes(x=x, y=y)) | ||
| + geom_area(fill=color, alpha=alpha, **kwargs) | ||
| + geom_line(color=line_color, size=line_width) | ||
| + labs(title=title or "Area Chart", x=xlabel or x, y=ylabel or y) | ||
| + theme_minimal() | ||
| + theme( | ||
| figure_size=(width, height), | ||
| plot_title=element_text(size=14, weight="bold", ha="center"), | ||
| axis_title=element_text(size=11), | ||
| axis_text=element_text(size=10), | ||
| panel_grid_major=element_line(alpha=0.3, linetype="dashed"), | ||
| panel_grid_minor=element_line(alpha=0), | ||
| ) | ||
| ) | ||
|
|
||
| return plot | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # Sample data for testing - simulating time series data | ||
| np.random.seed(42) # For reproducibility | ||
|
|
||
| # Generate sample time series data (e.g., monthly website visitors) | ||
| months = pd.date_range(start="2024-01-01", periods=12, freq="MS") | ||
|
|
||
| # Create realistic-looking growth pattern with some variation | ||
| base_values = np.linspace(1000, 2500, 12) | ||
| noise = np.random.normal(0, 150, 12) | ||
| values = base_values + noise | ||
|
|
||
| # Ensure no negative values | ||
| values = np.maximum(values, 100) | ||
|
|
||
| data = pd.DataFrame( | ||
| { | ||
| "Month": range(1, 13), # Use numeric for simpler plotting | ||
| "Visitors": values, | ||
| } | ||
| ) | ||
|
|
||
| # Create plot | ||
| plot = create_plot( | ||
| data, | ||
| x="Month", | ||
| y="Visitors", | ||
| title="Monthly Website Visitors (2024)", | ||
| xlabel="Month", | ||
| ylabel="Number of Visitors", | ||
| color="#3498db", | ||
| alpha=0.5, | ||
| line_color="#2980b9", | ||
| line_width=2, | ||
| # Data - monthly sales example from spec | ||
| data = pd.DataFrame( | ||
| { | ||
| "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "sales": [120, 135, 148, 162, 175, 195, 210, 198, 185, 170, 158, 190], | ||
| } | ||
| ) | ||
|
|
||
| # Convert month to ordered categorical for proper x-axis ordering | ||
| data["month"] = pd.Categorical( | ||
| data["month"], | ||
| categories=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| ordered=True, | ||
| ) | ||
|
|
||
| # Plot | ||
| plot = ( | ||
| ggplot(data, aes(x="month", y="sales", group=1)) | ||
| + geom_area(fill="#306998", alpha=0.6) | ||
| + geom_line(color="#306998", size=2) | ||
| + labs(title="Monthly Sales Trend", x="Month", y="Sales") | ||
| + theme_minimal() | ||
| + theme( | ||
| figure_size=(16, 9), | ||
| plot_title=element_text(size=20, weight="bold", ha="center"), | ||
| axis_title=element_text(size=20), | ||
| axis_text=element_text(size=16), | ||
| panel_grid_major=element_line(alpha=0.3), | ||
| panel_grid_minor=element_line(alpha=0), | ||
| ) | ||
| ) | ||
|
|
||
| # Save for inspection | ||
| plot.save("plot.png", dpi=300, verbose=False) | ||
| print("Plot saved to plot.png") | ||
| # Save | ||
| plot.save("plot.png", dpi=300, verbose=False) |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (plotnine ggplot in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/plotnine/line/line-basic/default.py.
| """ | ||
| area-basic: Basic Area Chart | ||
| Implementation for: plotly | ||
| Variant: default | ||
| Python: 3.10+ | ||
| Library: plotly | ||
| """ | ||
|
|
||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| import pandas as pd | ||
| import plotly.graph_objects as go | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| pass | ||
|
|
||
|
|
||
| def create_plot( | ||
| data: pd.DataFrame, | ||
| x: str, | ||
| y: str, | ||
| title: Optional[str] = None, | ||
| xlabel: Optional[str] = None, | ||
| ylabel: Optional[str] = None, | ||
| color: str = "rgba(99, 110, 250, 0.5)", | ||
| line_color: Optional[str] = None, | ||
| line_width: float = 2.0, | ||
| fill_to: str = "tozeroy", | ||
| height: int = 900, | ||
| width: int = 1600, | ||
| **kwargs, | ||
| ) -> go.Figure: | ||
| """ | ||
| Create a basic area chart showing quantitative data over a continuous interval. | ||
|
|
||
| The area between the line and the x-axis is filled with color, emphasizing | ||
| the magnitude of values. Ideal for showing trends and cumulative totals. | ||
|
|
||
| Args: | ||
| data: Input DataFrame with required columns | ||
| x: Column name for x-axis values (typically time or sequential data) | ||
| y: Column name for y-axis values (numeric) | ||
| title: Plot title (optional) | ||
| xlabel: Custom x-axis label (optional, defaults to column name) | ||
| ylabel: Custom y-axis label (optional, defaults to column name) | ||
| color: Fill color for the area with alpha (default: semi-transparent blue) | ||
| line_color: Color of the line at top of area (default: derived from fill color) | ||
| line_width: Width of the line (default: 2.0) | ||
| fill_to: Fill mode - 'tozeroy', 'tonexty', 'none' (default: 'tozeroy') | ||
| height: Figure height in pixels (default: 900) | ||
| width: Figure width in pixels (default: 1600) | ||
| **kwargs: Additional parameters passed to plotly Scatter trace | ||
|
|
||
| Returns: | ||
| Plotly Figure object | ||
|
|
||
| Raises: | ||
| ValueError: If data is empty | ||
| KeyError: If required columns not found | ||
|
|
||
| Example: | ||
| >>> data = pd.DataFrame({ | ||
| ... 'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'], | ||
| ... 'Sales': [100, 150, 130, 180, 200] | ||
| ... }) | ||
| >>> fig = create_plot(data, x='Month', y='Sales', title='Monthly Sales') | ||
| """ | ||
| # Input validation | ||
| if data.empty: | ||
| raise ValueError("Data cannot be empty") | ||
|
|
||
| # Check required columns | ||
| for col in [x, y]: | ||
| if col not in data.columns: | ||
| available = ", ".join(data.columns) | ||
| raise KeyError(f"Column '{col}' not found. Available columns: {available}") | ||
|
|
||
| # Derive line color from fill color if not provided | ||
| if line_color is None: | ||
| # Use a solid version of the fill color (darker) | ||
| line_color = "rgb(99, 110, 250)" | ||
|
|
||
| # Create the figure | ||
| fig = go.Figure() | ||
|
|
||
| # Add the area trace | ||
| fig.add_trace( | ||
| go.Scatter( | ||
| x=data[x], | ||
| y=data[y], | ||
| mode="lines", | ||
| fill=fill_to, | ||
| fillcolor=color, | ||
| line={"color": line_color, "width": line_width}, | ||
| name=y, | ||
| hovertemplate=f"<b>{x}</b>: %{{x}}<br><b>{y}</b>: %{{y:,.2f}}<extra></extra>", | ||
| **kwargs, | ||
| ) | ||
| # Data | ||
| data = pd.DataFrame( | ||
| { | ||
| "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "sales": [120, 135, 148, 162, 175, 195, 210, 198, 185, 170, 158, 190], | ||
| } | ||
| ) | ||
|
|
||
| # Create figure | ||
| fig = go.Figure() | ||
|
|
||
| fig.add_trace( | ||
| go.Scatter( | ||
| x=data["month"], | ||
| y=data["sales"], | ||
| mode="lines", | ||
| fill="tozeroy", | ||
| fillcolor="rgba(48, 105, 152, 0.5)", | ||
| line={"color": "#306998", "width": 2}, | ||
| name="Sales", | ||
| ) | ||
|
|
||
| # Update layout for professional appearance | ||
| fig.update_layout( | ||
| title={ | ||
| "text": title or "Area Chart", | ||
| "font": {"size": 18, "family": "Arial, sans-serif"}, | ||
| "x": 0.5, | ||
| "xanchor": "center", | ||
| }, | ||
| xaxis={ | ||
| "title": {"text": xlabel or x, "font": {"size": 14}}, | ||
| "showgrid": True, | ||
| "gridcolor": "rgba(128, 128, 128, 0.3)", | ||
| "gridwidth": 1, | ||
| "zeroline": False, | ||
| "showline": True, | ||
| "linewidth": 1, | ||
| "linecolor": "rgba(128, 128, 128, 0.5)", | ||
| }, | ||
| yaxis={ | ||
| "title": {"text": ylabel or y, "font": {"size": 14}}, | ||
| "showgrid": True, | ||
| "gridcolor": "rgba(128, 128, 128, 0.3)", | ||
| "gridwidth": 1, | ||
| "zeroline": True, | ||
| "zerolinewidth": 1, | ||
| "zerolinecolor": "rgba(128, 128, 128, 0.5)", | ||
| "showline": True, | ||
| "linewidth": 1, | ||
| "linecolor": "rgba(128, 128, 128, 0.5)", | ||
| }, | ||
| plot_bgcolor="white", | ||
| paper_bgcolor="white", | ||
| height=height, | ||
| width=width, | ||
| showlegend=False, | ||
| hovermode="x unified", | ||
| hoverlabel={"bgcolor": "white", "font_size": 12, "font_family": "Arial, sans-serif"}, | ||
| margin={"l": 80, "r": 40, "t": 80, "b": 60}, | ||
| ) | ||
|
|
||
| return fig | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import numpy as np | ||
|
|
||
| # Sample data: Monthly website traffic over a year | ||
| np.random.seed(42) | ||
|
|
||
| months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] | ||
|
|
||
| # Generate realistic traffic pattern with seasonal variation | ||
| base_traffic = 10000 | ||
| seasonal_factor = [0.8, 0.85, 0.95, 1.0, 1.1, 1.15, 1.2, 1.25, 1.1, 1.0, 0.9, 0.95] | ||
| noise = np.random.normal(0, 500, 12) | ||
|
|
||
| traffic = [int(base_traffic * sf + n) for sf, n in zip(seasonal_factor, noise, strict=False)] | ||
|
|
||
| data = pd.DataFrame({"Month": months, "Visitors": traffic}) | ||
|
|
||
| # Create the area chart | ||
| fig = create_plot( | ||
| data, | ||
| x="Month", | ||
| y="Visitors", | ||
| title="Monthly Website Visitors (2024)", | ||
| xlabel="Month", | ||
| ylabel="Number of Visitors", | ||
| color="rgba(99, 110, 250, 0.4)", | ||
| line_color="rgb(99, 110, 250)", | ||
| line_width=2.5, | ||
| ) | ||
|
|
||
| # Save as PNG | ||
| fig.write_image("plot.png", width=1600, height=900, scale=2) | ||
| print("Plot saved to plot.png") | ||
| ) | ||
|
|
||
| # Layout | ||
| fig.update_layout( | ||
| title={"text": "Monthly Sales Trend", "font": {"size": 20}, "x": 0.5, "xanchor": "center"}, | ||
| xaxis_title={"text": "Month", "font": {"size": 20}}, | ||
| yaxis_title={"text": "Sales ($)", "font": {"size": 20}}, | ||
| template="plotly_white", | ||
| xaxis={"tickfont": {"size": 16}, "showgrid": True, "gridcolor": "rgba(0, 0, 0, 0.1)"}, | ||
| yaxis={"tickfont": {"size": 16}, "showgrid": True, "gridcolor": "rgba(0, 0, 0, 0.1)"}, | ||
| showlegend=False, | ||
| margin={"l": 80, "r": 40, "t": 80, "b": 80}, | ||
| ) | ||
|
|
||
| # Save | ||
| fig.write_image("plot.png", width=1600, height=900, scale=3) |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (plotly Figure in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/plotly/line/line-basic/default.py.
| """ | ||
| area-basic: Basic Area Chart | ||
| Library: highcharts | ||
| """ | ||
|
|
||
| import tempfile | ||
| import time | ||
| import urllib.request | ||
| from pathlib import Path | ||
|
|
||
| from highcharts_core.chart import Chart | ||
| from highcharts_core.options import HighchartsOptions | ||
| from highcharts_core.options.series.area import AreaSeries | ||
| from selenium import webdriver | ||
| from selenium.webdriver.chrome.options import Options | ||
|
|
||
|
|
||
| # Data - Monthly sales example | ||
| sales = [100, 150, 130, 180, 200, 220, 195, 240, 280, 310, 290, 350] | ||
|
|
||
| # Create chart | ||
| chart = Chart(container="container") | ||
| chart.options = HighchartsOptions() | ||
|
|
||
| # Chart configuration | ||
| chart.options.chart = { | ||
| "type": "area", | ||
| "width": 4800, | ||
| "height": 2700, | ||
| "backgroundColor": "#ffffff", | ||
| "style": {"fontFamily": "Arial, sans-serif"}, | ||
| } | ||
|
|
||
| # Title | ||
| chart.options.title = {"text": "Monthly Sales Trend", "style": {"fontSize": "48px"}} | ||
|
|
||
| # Axes | ||
| chart.options.x_axis = { | ||
| "title": {"text": "Month", "style": {"fontSize": "40px"}}, | ||
| "categories": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "labels": {"style": {"fontSize": "32px"}, "enabled": True}, | ||
| "gridLineWidth": 1, | ||
| "gridLineColor": "rgba(0, 0, 0, 0.1)", | ||
| "tickmarkPlacement": "on", | ||
| } | ||
|
|
||
| chart.options.y_axis = { | ||
| "title": {"text": "Sales ($)", "style": {"fontSize": "40px"}}, | ||
| "labels": {"style": {"fontSize": "32px"}}, | ||
| "gridLineWidth": 1, | ||
| "gridLineColor": "rgba(0, 0, 0, 0.1)", | ||
| } | ||
|
|
||
| # Legend | ||
| chart.options.legend = {"enabled": False} | ||
|
|
||
| # Create area series | ||
| series = AreaSeries() | ||
| series.data = sales | ||
| series.name = "Sales" | ||
| series.color = "#306998" | ||
| series.fill_opacity = 0.5 | ||
| series.line_width = 4 | ||
| series.marker = {"enabled": True, "radius": 6, "fillColor": "#306998", "lineWidth": 2, "lineColor": "#ffffff"} | ||
|
|
||
| chart.add_series(series) | ||
|
|
||
| # Download Highcharts JS | ||
| highcharts_url = "https://code.highcharts.com/highcharts.js" | ||
| with urllib.request.urlopen(highcharts_url, timeout=30) as response: | ||
| highcharts_js = response.read().decode("utf-8") | ||
|
|
||
| # Generate HTML with inline scripts | ||
| html_str = chart.to_js_literal() | ||
| html_content = f"""<!DOCTYPE html> | ||
| <html> | ||
| <head> | ||
| <meta charset="utf-8"> | ||
| <script>{highcharts_js}</script> | ||
| </head> | ||
| <body style="margin:0;"> | ||
| <div id="container" style="width: 4800px; height: 2700px;"></div> | ||
| <script>{html_str}</script> | ||
| </body> | ||
| </html>""" | ||
|
|
||
| # Write temp HTML and take screenshot | ||
| with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False, encoding="utf-8") as f: | ||
| f.write(html_content) | ||
| temp_path = f.name | ||
|
|
||
| chrome_options = Options() | ||
| chrome_options.add_argument("--headless") | ||
| chrome_options.add_argument("--no-sandbox") | ||
| chrome_options.add_argument("--disable-dev-shm-usage") | ||
| chrome_options.add_argument("--disable-gpu") | ||
| chrome_options.add_argument("--window-size=4800,2800") | ||
|
|
||
| driver = webdriver.Chrome(options=chrome_options) | ||
| driver.set_window_size(4800, 2800) | ||
| driver.get(f"file://{temp_path}") | ||
| time.sleep(5) | ||
|
|
||
| # Get the container element and screenshot it directly | ||
| container = driver.find_element("id", "container") | ||
| container.screenshot("plot.png") | ||
| driver.quit() | ||
|
|
||
| Path(temp_path).unlink() |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (highcharts Chart in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/highcharts/line/line-basic/default.py.
| """ | ||
| area-basic: Basic Area Chart | ||
| Implementation for: bokeh | ||
| Variant: default | ||
| Python: 3.10+ | ||
| Library: bokeh | ||
| """ | ||
|
|
||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| import pandas as pd | ||
| from bokeh.io import export_png | ||
| from bokeh.models import ColumnDataSource | ||
| from bokeh.plotting import figure | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from bokeh.plotting import Figure | ||
|
|
||
|
|
||
| def create_plot( | ||
| data: pd.DataFrame, | ||
| x: str, | ||
| y: str, | ||
| fill_alpha: float = 0.5, | ||
| line_color: Optional[str] = None, | ||
| title: Optional[str] = None, | ||
| x_label: Optional[str] = None, | ||
| y_label: Optional[str] = None, | ||
| width: int = 1600, | ||
| height: int = 900, | ||
| **kwargs, | ||
| ) -> "Figure": | ||
| """ | ||
| Create a basic filled area chart using bokeh. | ||
|
|
||
| A simple filled area chart showing a single data series over time or | ||
| sequential x-values. The area between the data line and the baseline | ||
| (zero) is filled with a semi-transparent color. | ||
|
|
||
| Args: | ||
| data: Input DataFrame with x and y columns | ||
| x: Column name for x-axis values | ||
| y: Column name for y-axis values | ||
| fill_alpha: Transparency of the filled area (default: 0.5) | ||
| line_color: Color of the line and fill (default: bokeh blue) | ||
| title: Chart title (optional) | ||
| x_label: Label for x-axis (optional, defaults to column name) | ||
| y_label: Label for y-axis (optional, defaults to column name) | ||
| width: Figure width in pixels (default: 1600) | ||
| height: Figure height in pixels (default: 900) | ||
| **kwargs: Additional parameters passed to figure | ||
|
|
||
| Returns: | ||
| Bokeh Figure object | ||
|
|
||
| Raises: | ||
| ValueError: If data is empty or fill_alpha is out of range | ||
| KeyError: If required columns not found | ||
|
|
||
| Example: | ||
| >>> data = pd.DataFrame({ | ||
| ... 'Month': [1, 2, 3, 4, 5, 6], | ||
| ... 'Sales': [100, 120, 90, 140, 160, 130] | ||
| ... }) | ||
| >>> fig = create_plot(data, x='Month', y='Sales', title='Monthly Sales') | ||
| """ | ||
| # Input validation | ||
| if data.empty: | ||
| raise ValueError("Data cannot be empty") | ||
|
|
||
| for col in [x, y]: | ||
| if col not in data.columns: | ||
| available = ", ".join(data.columns) | ||
| raise KeyError(f"Column '{col}' not found. Available columns: {available}") | ||
|
|
||
| if not 0 <= fill_alpha <= 1: | ||
| raise ValueError(f"fill_alpha must be between 0 and 1, got {fill_alpha}") | ||
|
|
||
| # Set default color (bokeh blue) | ||
| color = line_color or "#1f77b4" | ||
|
|
||
| # Sort data by x to ensure proper area rendering | ||
| plot_data = data[[x, y]].dropna().sort_values(by=x).reset_index(drop=True) | ||
|
|
||
| # Create ColumnDataSource | ||
| source = ColumnDataSource(data={"x": plot_data[x], "y": plot_data[y], "y0": [0] * len(plot_data)}) | ||
|
|
||
| # Create figure | ||
| p = figure( | ||
| width=width, | ||
| height=height, | ||
| title=title or "Area Chart", | ||
| x_axis_label=x_label or x, | ||
| y_axis_label=y_label or y, | ||
| toolbar_location="above", | ||
| tools="pan,wheel_zoom,box_zoom,reset,save", | ||
| **kwargs, | ||
| ) | ||
|
|
||
| # Draw the filled area from baseline (0) to y values | ||
| p.varea(x="x", y1="y0", y2="y", source=source, fill_color=color, fill_alpha=fill_alpha) | ||
|
|
||
| # Draw line on top for better visibility | ||
| p.line(x="x", y="y", source=source, line_color=color, line_width=2) | ||
|
|
||
| # Styling | ||
| p.title.text_font_size = "14pt" | ||
| p.title.align = "center" | ||
|
|
||
| # Grid styling - subtle | ||
| p.xgrid.grid_line_alpha = 0.3 | ||
| p.ygrid.grid_line_alpha = 0.3 | ||
| p.xgrid.grid_line_dash = [6, 4] | ||
| p.ygrid.grid_line_dash = [6, 4] | ||
|
|
||
| # Axis styling | ||
| p.xaxis.axis_label_text_font_size = "12pt" | ||
| p.yaxis.axis_label_text_font_size = "12pt" | ||
| p.xaxis.major_label_text_font_size = "10pt" | ||
| p.yaxis.major_label_text_font_size = "10pt" | ||
|
|
||
| return p | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import numpy as np | ||
|
|
||
| # Sample data: Monthly website traffic over a year | ||
| np.random.seed(42) | ||
| months = list(range(1, 13)) | ||
| base_traffic = [1000, 1100, 1050, 1200, 1400, 1600, 1500, 1550, 1700, 1650, 1800, 2000] | ||
| noise = np.random.normal(0, 50, 12) | ||
| traffic = [max(0, int(b + n)) for b, n in zip(base_traffic, noise, strict=False)] | ||
|
|
||
| data = pd.DataFrame({"Month": months, "Visitors": traffic}) | ||
|
|
||
| # Create plot | ||
| fig = create_plot( | ||
| data, | ||
| x="Month", | ||
| y="Visitors", | ||
| title="Monthly Website Traffic", | ||
| x_label="Month", | ||
| y_label="Visitors (thousands)", | ||
| fill_alpha=0.5, | ||
| ) | ||
|
|
||
| # Save as PNG using webdriver-manager for automatic chromedriver | ||
| from bokeh.io import export_png | ||
| from selenium import webdriver | ||
| from selenium.webdriver.chrome.options import Options | ||
| from selenium.webdriver.chrome.service import Service | ||
| from webdriver_manager.chrome import ChromeDriverManager | ||
|
|
||
| chrome_options = Options() | ||
| chrome_options.add_argument("--headless") | ||
| chrome_options.add_argument("--no-sandbox") | ||
| chrome_options.add_argument("--disable-dev-shm-usage") | ||
|
|
||
| service = Service(ChromeDriverManager().install()) | ||
| driver = webdriver.Chrome(service=service, options=chrome_options) | ||
|
|
||
| export_png(fig, filename="plot.png", webdriver=driver) | ||
| driver.quit() | ||
| print("Plot saved to plot.png") | ||
| # Data | ||
| data = pd.DataFrame( | ||
| { | ||
| "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "sales": [120, 135, 148, 162, 175, 195, 210, 198, 185, 170, 158, 190], | ||
| } | ||
| ) | ||
|
|
||
| # Create x positions for categorical months | ||
| x = list(range(len(data["month"]))) | ||
| y = data["sales"].tolist() | ||
|
|
||
| source = ColumnDataSource(data={"x": x, "y": y, "month": data["month"]}) | ||
|
|
||
| # Create figure | ||
| p = figure( | ||
| width=4800, | ||
| height=2700, | ||
| title="Monthly Sales Volume", | ||
| x_axis_label="Month", | ||
| y_axis_label="Sales ($)", | ||
| x_range=(-0.5, len(x) - 0.5), | ||
| ) | ||
|
|
||
| # Plot area (varea fills from y1 to y2) | ||
| p.varea(x="x", y1=0, y2="y", source=source, fill_alpha=0.7, fill_color="#306998") | ||
|
|
||
| # Add line on top for clearer boundary | ||
| p.line(x="x", y="y", source=source, line_width=2, line_color="#306998") | ||
|
|
||
| # Configure x-axis ticks to show month labels | ||
| p.xaxis.ticker = x | ||
| p.xaxis.major_label_overrides = dict(enumerate(data["month"])) | ||
|
|
||
| # Styling | ||
| p.title.text_font_size = "20pt" | ||
| p.xaxis.axis_label_text_font_size = "20pt" | ||
| p.yaxis.axis_label_text_font_size = "20pt" | ||
| p.xaxis.major_label_text_font_size = "16pt" | ||
| p.yaxis.major_label_text_font_size = "16pt" | ||
| p.grid.grid_line_alpha = 0.3 | ||
|
|
||
| # Save | ||
| export_png(p, filename="plot.png") |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (bokeh Figure in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/bokeh/line/line-basic/default.py.
| """ | ||
| area-basic: Basic Area Chart | ||
| Implementation for: seaborn | ||
| Variant: default | ||
| Python: 3.10+ | ||
|
|
||
| Note: Seaborn does not have a native area chart function. This implementation | ||
| uses matplotlib's fill_between with seaborn's styling for a consistent look. | ||
| Library: seaborn | ||
| """ | ||
|
|
||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| import matplotlib.pyplot as plt | ||
| import pandas as pd | ||
| import seaborn as sns | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from matplotlib.figure import Figure | ||
|
|
||
|
|
||
| def create_plot( | ||
| data: pd.DataFrame, | ||
| x: str, | ||
| y: str, | ||
| color: str = "steelblue", | ||
| alpha: float = 0.4, | ||
| line_alpha: float = 1.0, | ||
| title: Optional[str] = None, | ||
| xlabel: Optional[str] = None, | ||
| ylabel: Optional[str] = None, | ||
| figsize: tuple[float, float] = (16, 9), | ||
| **kwargs, | ||
| ) -> "Figure": | ||
| """ | ||
| Create a basic filled area chart using seaborn styling with matplotlib. | ||
|
|
||
| Args: | ||
| data: Input DataFrame with required columns | ||
| x: Column name for x-axis values (sequential: datetime, numeric, or categorical) | ||
| y: Column name for y-axis values (numeric) | ||
| color: Fill and line color (default: "steelblue") | ||
| alpha: Transparency level for area fill 0.0-1.0 (default: 0.4) | ||
| line_alpha: Transparency level for edge line 0.0-1.0 (default: 1.0) | ||
| title: Plot title (default: None) | ||
| xlabel: Custom x-axis label (default: column name) | ||
| ylabel: Custom y-axis label (default: column name) | ||
| figsize: Figure size as (width, height) (default: (16, 9)) | ||
| **kwargs: Additional parameters passed to fill_between() | ||
|
|
||
| Returns: | ||
| Matplotlib Figure object | ||
|
|
||
| Raises: | ||
| ValueError: If data is empty | ||
| KeyError: If required columns not found | ||
|
|
||
| Example: | ||
| >>> data = pd.DataFrame({'Month': range(1, 13), 'Revenue': [10, 15, 13, 17, 20, 25, 22, 26, 24, 28, 30, 35]}) | ||
| >>> fig = create_plot(data, x='Month', y='Revenue') | ||
| """ | ||
| # Input validation | ||
| if data.empty: | ||
| raise ValueError("Data cannot be empty") | ||
|
|
||
| # Check required columns | ||
| for col in [x, y]: | ||
| if col not in data.columns: | ||
| available = ", ".join(data.columns) | ||
| raise KeyError(f"Column '{col}' not found. Available: {available}") | ||
|
|
||
| # Set seaborn style for consistent appearance | ||
| sns.set_theme(style="whitegrid") | ||
|
|
||
| # Create figure | ||
| fig, ax = plt.subplots(figsize=figsize) | ||
|
|
||
| # Get x and y values | ||
| x_vals = data[x] | ||
| y_vals = data[y] | ||
|
|
||
| # Plot the edge line first | ||
| ax.plot(x_vals, y_vals, color=color, alpha=line_alpha, linewidth=2) | ||
|
|
||
| # Fill the area between the line and baseline (y=0) | ||
| ax.fill_between(x_vals, y_vals, alpha=alpha, color=color, **kwargs) | ||
|
|
||
| # Apply styling | ||
| ax.set_xlabel(xlabel or x, fontsize=12) | ||
| ax.set_ylabel(ylabel or y, fontsize=12) | ||
| ax.grid(True, alpha=0.3, linestyle="--") | ||
|
|
||
| # Set y-axis to start from 0 for area charts (standard practice) | ||
| y_min = min(0, y_vals.min()) | ||
| y_max = y_vals.max() | ||
| y_padding = (y_max - y_min) * 0.05 | ||
| ax.set_ylim(y_min, y_max + y_padding) | ||
|
|
||
| # Title | ||
| if title: | ||
| ax.set_title(title, fontsize=14, fontweight="bold") | ||
| # Data - monthly sales over a year | ||
| data = pd.DataFrame( | ||
| { | ||
| "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "sales": [120, 135, 148, 162, 175, 195, 210, 198, 185, 170, 158, 190], | ||
| } | ||
| ) | ||
|
|
||
| # Tight layout to avoid label clipping | ||
| plt.tight_layout() | ||
| # Set seaborn style | ||
| sns.set_theme(style="whitegrid") | ||
|
|
||
| return fig | ||
| # Create figure | ||
| fig, ax = plt.subplots(figsize=(16, 9)) | ||
|
|
||
| # Plot line and filled area (seaborn doesn't have native area chart, use matplotlib) | ||
| ax.plot(data["month"], data["sales"], color="#306998", linewidth=2) | ||
| ax.fill_between(data["month"], data["sales"], alpha=0.4, color="#306998") | ||
|
|
||
| if __name__ == "__main__": | ||
| # Sample data for testing - monthly revenue over a year | ||
| data = pd.DataFrame( | ||
| { | ||
| "Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], | ||
| "Revenue": [12000, 15000, 13500, 17000, 20000, 25000, 22000, 26000, 24000, 28000, 30000, 35000], | ||
| } | ||
| ) | ||
| # Labels and styling | ||
| ax.set_xlabel("Month", fontsize=20) | ||
| ax.set_ylabel("Sales", fontsize=20) | ||
| ax.set_title("Basic Area Chart", fontsize=20) | ||
| ax.tick_params(axis="both", labelsize=16) | ||
| ax.grid(True, alpha=0.3, linestyle="--") | ||
|
|
||
| # Create plot | ||
| fig = create_plot(data, x="Month", y="Revenue", title="Monthly Revenue Growth", ylabel="Revenue ($)") | ||
| # Set y-axis to start from 0 for proper area representation | ||
| ax.set_ylim(0, max(data["sales"]) * 1.1) | ||
|
|
||
| # Save for inspection | ||
| plt.savefig("plot.png", dpi=300, bbox_inches="tight") | ||
| print("Plot saved to plot.png") | ||
| plt.tight_layout() | ||
| plt.savefig("plot.png", dpi=300, bbox_inches="tight") |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/matplotlib/plot/line-basic/default.py or plots/seaborn/lineplot/line-basic/default.py.
|
|
||
|
|
||
| # Data - monthly sales example from spec | ||
| months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] | ||
| sales = [100, 150, 130, 180, 200, 220] | ||
|
|
||
| # Custom style with project palette | ||
| custom_style = Style( | ||
| background="white", | ||
| plot_background="white", | ||
| foreground="#333333", | ||
| foreground_strong="#333333", | ||
| foreground_subtle="#666666", | ||
| colors=("#306998",), | ||
| font_family="sans-serif", | ||
| title_font_size=60, | ||
| label_font_size=48, | ||
| major_label_font_size=48, | ||
| legend_font_size=48, | ||
| value_font_size=36, | ||
| opacity=0.5, | ||
| opacity_hover=0.7, | ||
| ) | ||
|
|
||
| # Create area chart (Line chart with fill=True) | ||
| chart = pygal.Line( | ||
| width=4800, | ||
| height=2700, | ||
| title="Monthly Sales", | ||
| x_title="Month", | ||
| y_title="Sales ($)", | ||
| style=custom_style, | ||
| show_legend=False, | ||
| fill=True, | ||
| show_x_guides=False, | ||
| show_y_guides=True, | ||
| dots_size=8, | ||
| stroke_style={"width": 4}, | ||
| ) | ||
|
|
||
| # Add data | ||
| chart.x_labels = months | ||
| chart.add("Sales", sales) | ||
|
|
||
| # Save | ||
| chart.render_to_png("plot.png") |
There was a problem hiding this comment.
This implementation is missing the required create_plot() function. All plot implementations in this project must follow the standard pattern:
-
Define a
create_plot(data: pd.DataFrame, x: str, y: str, **params)function with:- Proper type hints (use
TYPE_CHECKINGfor forward references) - Comprehensive docstring with Args, Returns, Raises, and Example sections
- Input validation (empty data, missing columns, data type checks)
- Parameter handling with sensible defaults
- Return the appropriate plot object (pygal Line chart in this case)
- Proper type hints (use
-
Use
if __name__ == "__main__":block for example/test code
The current implementation has hardcoded data in the main body, which prevents the plot from being used programmatically via the API. Please restructure this to match the pattern used in existing implementations like plots/pygal/line/line-basic/default.py.
| # Data - monthly sales example from spec | |
| months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] | |
| sales = [100, 150, 130, 180, 200, 220] | |
| # Custom style with project palette | |
| custom_style = Style( | |
| background="white", | |
| plot_background="white", | |
| foreground="#333333", | |
| foreground_strong="#333333", | |
| foreground_subtle="#666666", | |
| colors=("#306998",), | |
| font_family="sans-serif", | |
| title_font_size=60, | |
| label_font_size=48, | |
| major_label_font_size=48, | |
| legend_font_size=48, | |
| value_font_size=36, | |
| opacity=0.5, | |
| opacity_hover=0.7, | |
| ) | |
| # Create area chart (Line chart with fill=True) | |
| chart = pygal.Line( | |
| width=4800, | |
| height=2700, | |
| title="Monthly Sales", | |
| x_title="Month", | |
| y_title="Sales ($)", | |
| style=custom_style, | |
| show_legend=False, | |
| fill=True, | |
| show_x_guides=False, | |
| show_y_guides=True, | |
| dots_size=8, | |
| stroke_style={"width": 4}, | |
| ) | |
| # Add data | |
| chart.x_labels = months | |
| chart.add("Sales", sales) | |
| # Save | |
| chart.render_to_png("plot.png") | |
| import pandas as pd | |
| from typing import TYPE_CHECKING, Any | |
| if TYPE_CHECKING: | |
| from pygal import Line | |
| def create_plot( | |
| data: pd.DataFrame, | |
| x: str, | |
| y: str, | |
| *, | |
| title: str = "Monthly Sales", | |
| x_title: str = "Month", | |
| y_title: str = "Sales ($)", | |
| color: str = "#306998", | |
| width: int = 4800, | |
| height: int = 2700, | |
| fill: bool = True, | |
| show_legend: bool = False, | |
| show_x_guides: bool = False, | |
| show_y_guides: bool = True, | |
| dots_size: int = 8, | |
| stroke_width: int = 4, | |
| opacity: float = 0.5, | |
| opacity_hover: float = 0.7, | |
| style: Style = None, | |
| **params: Any, | |
| ) -> "Line": | |
| """ | |
| Create a basic area chart using pygal. | |
| Args: | |
| data (pd.DataFrame): Input data. | |
| x (str): Column name for x-axis (categorical). | |
| y (str): Column name for y-axis (numeric). | |
| title (str, optional): Chart title. Defaults to "Monthly Sales". | |
| x_title (str, optional): X-axis label. Defaults to "Month". | |
| y_title (str, optional): Y-axis label. Defaults to "Sales ($)". | |
| color (str, optional): Area color. Defaults to "#306998". | |
| width (int, optional): Chart width in px. Defaults to 4800. | |
| height (int, optional): Chart height in px. Defaults to 2700. | |
| fill (bool, optional): Fill area under line. Defaults to True. | |
| show_legend (bool, optional): Show legend. Defaults to False. | |
| show_x_guides (bool, optional): Show x-axis grid lines. Defaults to False. | |
| show_y_guides (bool, optional): Show y-axis grid lines. Defaults to True. | |
| dots_size (int, optional): Size of dots. Defaults to 8. | |
| stroke_width (int, optional): Line width. Defaults to 4. | |
| opacity (float, optional): Area opacity. Defaults to 0.5. | |
| opacity_hover (float, optional): Opacity on hover. Defaults to 0.7. | |
| style (Style, optional): Custom pygal style. If None, uses default project style. | |
| **params: Additional keyword arguments for pygal.Line. | |
| Returns: | |
| pygal.Line: Configured pygal Line chart object (with fill=True for area). | |
| Raises: | |
| ValueError: If data is empty, or columns are missing/invalid. | |
| TypeError: If y column is not numeric. | |
| Example: | |
| >>> import pandas as pd | |
| >>> df = pd.DataFrame({'Month': ['Jan', 'Feb'], 'Sales': [100, 150]}) | |
| >>> chart = create_plot(df, x='Month', y='Sales') | |
| >>> chart.render_to_png('plot.png') | |
| """ | |
| if data is None or data.empty: | |
| raise ValueError("Input data is empty.") | |
| if x not in data.columns: | |
| raise ValueError(f"Column '{x}' not found in data.") | |
| if y not in data.columns: | |
| raise ValueError(f"Column '{y}' not found in data.") | |
| if not pd.api.types.is_numeric_dtype(data[y]): | |
| raise TypeError(f"Column '{y}' must be numeric.") | |
| x_labels = data[x].astype(str).tolist() | |
| y_values = data[y].tolist() | |
| if style is None: | |
| style = Style( | |
| background="white", | |
| plot_background="white", | |
| foreground="#333333", | |
| foreground_strong="#333333", | |
| foreground_subtle="#666666", | |
| colors=(color,), | |
| font_family="sans-serif", | |
| title_font_size=60, | |
| label_font_size=48, | |
| major_label_font_size=48, | |
| legend_font_size=48, | |
| value_font_size=36, | |
| opacity=opacity, | |
| opacity_hover=opacity_hover, | |
| ) | |
| chart = pygal.Line( | |
| width=width, | |
| height=height, | |
| title=title, | |
| x_title=x_title, | |
| y_title=y_title, | |
| style=style, | |
| show_legend=show_legend, | |
| fill=fill, | |
| show_x_guides=show_x_guides, | |
| show_y_guides=show_y_guides, | |
| dots_size=dots_size, | |
| stroke_style={"width": stroke_width}, | |
| **params, | |
| ) | |
| chart.x_labels = x_labels | |
| chart.add(y_title if not show_legend else y, y_values) | |
| return chart | |
| if __name__ == "__main__": | |
| # Example usage | |
| import pandas as pd | |
| months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] | |
| sales = [100, 150, 130, 180, 200, 220] | |
| df = pd.DataFrame({"Month": months, "Sales": sales}) | |
| chart = create_plot(df, x="Month", y="Sales") | |
| chart.render_to_png("plot.png") |
Summary
Adds
area-basicplot implementation.Libraries
Links
specs/area-basic.md🤖 Auto-generated by pyplots CI