Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 176 additions & 0 deletions plots/plotly/scatter/area-basic/default.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""
area-basic: Basic Area Chart
Implementation for: plotly
Variant: default
Python: 3.10+
"""

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,
)
)

# 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")
70 changes: 31 additions & 39 deletions specs/area-basic.md
Original file line number Diff line number Diff line change
@@ -1,63 +1,55 @@
# area-basic: Basic Area Chart

<!--
Spec Template Version: 1.0.0
Created: 2025-12-01
Last Updated: 2025-12-01
-->

**Spec Version:** 1.0.0

## Description

Create a simple area chart showing a filled region between the x-axis and a line.
Perfect for visualizing quantities over continuous intervals, trends over time, or cumulative values.
Works with any dataset containing a continuous x variable and numeric y values.
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.

## Data Requirements

- **x**: Values for the x-axis (numeric or datetime: continuous sequence)
- **y**: Numeric values defining the top of the filled area (numeric: continuous values)
- **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)

## Optional Parameters

- `color`: Fill color for the area (type: string, default: "steelblue")
- `alpha`: Transparency level for the filled area (type: float 0.0-1.0, default: 0.4)
- `line_color`: Color of the top edge line (type: string, default: same as fill color)
- `line_width`: Width of the top edge line (type: float, default: 2.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))
- `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')

## Quality Criteria

- [ ] X and Y axes are labeled with column names (or custom labels if provided)
- [ ] Grid is visible but subtle with alpha=0.3
- [ ] Filled area is clearly visible with appropriate transparency
- [ ] Top edge line is visible and distinguishes the data boundary
- [ ] No overlapping axis labels or tick marks
- [ ] Colorblind-safe colors (use accessible defaults)
- [ ] Appropriate figure size (16x9 default) for readability
- [ ] Title is centered and clearly readable if provided (fontsize 14, bold)
- [ ] 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)

## Expected Output

A clean area chart with a filled region extending from the x-axis up to the data values.
The filled area should have moderate transparency to show grid lines underneath while remaining clearly visible.
A solid line along the top edge should clearly define where the data values lie.
The plot should be immediately understandable without additional explanation.
All text elements (labels, title, and tick labels) should be legible at standard display sizes.
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

## Tags

trend, continuous, basic, area, time-series, statistical, exploratory
area, line, trend, timeseries, basic, 2d

## Use Cases

- Stock price visualization showing value over time (e.g., daily closing prices)
- Website traffic metrics over time (e.g., daily page views)
- Temperature variations throughout a day or season
- Revenue or sales trends over months or years
- Resource utilization over time (e.g., CPU usage, memory consumption)
- Population growth over time periods
- 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
Loading