diff --git a/plots/seaborn/fill_between/area-basic/default.py b/plots/seaborn/fill_between/area-basic/default.py new file mode 100644 index 0000000000..8e6f6e8f55 --- /dev/null +++ b/plots/seaborn/fill_between/area-basic/default.py @@ -0,0 +1,123 @@ +""" +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. +""" + +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") + + # Tight layout to avoid label clipping + plt.tight_layout() + + return fig + + +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], + } + ) + + # Create plot + fig = create_plot(data, x="Month", y="Revenue", title="Monthly Revenue Growth", ylabel="Revenue ($)") + + # Save for inspection + plt.savefig("plot.png", dpi=300, bbox_inches="tight") + print("Plot saved to plot.png") diff --git a/specs/area-basic.md b/specs/area-basic.md index d7d3c6dded..8df6bb9902 100644 --- a/specs/area-basic.md +++ b/specs/area-basic.md @@ -1,55 +1,62 @@ # area-basic: Basic Area Chart + + **Spec Version:** 1.0.0 ## Description -A basic area chart that displays quantitative data over a continuous interval or time period. The area between the line and the axis is filled with color, emphasizing the magnitude of values. Ideal for showing trends and cumulative totals over time. +Create a simple filled area chart showing a single data series over time or sequential x-values. +Perfect for visualizing cumulative values, trends with emphasis on magnitude, and comparing values to a baseline. +Works with any dataset containing sequential x-values and numeric y-values. ## Data Requirements -- **x**: Column for x-axis values (typically time or sequential data - numeric or datetime) -- **y**: Numeric column for y-axis values (the values to be plotted) +- **x**: Sequential values for x-axis (datetime, numeric, or categorical) +- **y**: Numeric values representing the area height at each x point ## Optional Parameters -- `title`: Plot title (default: None) -- `xlabel`: X-axis label (default: uses column name) -- `ylabel`: Y-axis label (default: uses column name) -- `color`: Fill color for the area (default: library-specific default) -- `alpha`: Transparency level for the fill (default: 0.5) -- `line_color`: Color of the line at the top of the area (default: same as color but darker) -- `line_width`: Width of the line (default: 2) -- `fill_to`: What to fill to - 'zero' or 'none' (default: 'zero') +- `color`: Fill color for the area (type: string, default: "steelblue") +- `alpha`: Transparency level for fill (type: float 0.0-1.0, default: 0.4) +- `line_alpha`: Transparency level for edge line (type: float 0.0-1.0, default: 1.0) +- `title`: Plot title (type: string, default: None) +- `xlabel`: Custom x-axis label (type: string, default: column name) +- `ylabel`: Custom y-axis label (type: string, default: column name) +- `figsize`: Figure size (type: tuple, default: (16, 9)) ## Quality Criteria -- [ ] X and Y axes are labeled with column names or custom labels -- [ ] Area fill is visible but not overwhelming (appropriate alpha) -- [ ] Line at top of area is clearly visible -- [ ] Grid is visible but subtle (alpha <= 0.3) -- [ ] No overlapping labels or tick marks -- [ ] Data accurately represented without distortion -- [ ] Appropriate figure size (16:9 aspect ratio) +- [ ] X and Y axes are labeled with column names (or custom labels if provided) +- [ ] Grid is visible but subtle with alpha=0.3 +- [ ] Area fill is clearly visible with appropriate transparency (alpha ~0.4) +- [ ] Edge line is visible to define the data boundary +- [ ] No overlapping axis labels or tick marks +- [ ] Colorblind-safe colors used +- [ ] Appropriate figure size (16x9 aspect ratio) for readability +- [ ] Title is centered and clearly readable if provided ## Expected Output -A filled area chart with: -- A colored area extending from the data line down to the x-axis (or zero line) -- A visible line tracing the top of the area -- Clear axis labels and optional title -- Subtle grid for readability -- Professional appearance suitable for presentations and reports +A clean area chart with a filled region between the data line and the x-axis baseline. +The fill should be semi-transparent to allow grid lines to show through while still emphasizing magnitude. +A solid edge line should clearly define the top boundary of the data. +The plot should be immediately understandable without additional explanation. +All text elements should be legible at standard display sizes. ## Tags -area, line, trend, timeseries, basic, 2d +area, trend, time-series, basic, magnitude, cumulative, exploratory ## Use Cases -- Visualizing stock price movements over time -- Displaying website traffic trends -- Showing cumulative sales or revenue over periods -- Tracking temperature changes throughout the day -- Monitoring resource usage (CPU, memory) over time -- Displaying population growth trends +- Visualizing cumulative values over time (e.g., total revenue growth) +- Showing trends with emphasis on magnitude (e.g., stock prices) +- Comparing values to a baseline (e.g., temperature above/below average) +- Website traffic visualization over time +- Resource utilization monitoring (CPU, memory usage) +- Population or growth trends