Skip to content

Commit 6d7253f

Browse files
feat(seaborn): implement line-basic
Add basic line plot implementation for seaborn library: - plots/seaborn/lineplot/line-basic/default.py - specs/line-basic.md Features: - Time series and trend visualization - Customizable line styles, markers, and colors - Data validation and type checking - Optional data sorting for proper line rendering - Follows project code quality standards
1 parent 58567b5 commit 6d7253f

2 files changed

Lines changed: 232 additions & 0 deletions

File tree

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
"""
2+
line-basic: Basic Line Plot
3+
Implementation for: seaborn
4+
Variant: default
5+
Python: 3.10+
6+
"""
7+
8+
from typing import TYPE_CHECKING, Optional
9+
10+
import matplotlib.pyplot as plt
11+
import numpy as np
12+
import pandas as pd
13+
import seaborn as sns
14+
15+
16+
if TYPE_CHECKING:
17+
from matplotlib.figure import Figure
18+
19+
20+
def create_plot(
21+
data: pd.DataFrame,
22+
x: str,
23+
y: str,
24+
figsize: tuple[float, float] = (16, 9),
25+
color: str = "steelblue",
26+
linewidth: float = 2.0,
27+
linestyle: str = "-",
28+
marker: Optional[str] = None,
29+
markersize: float = 6,
30+
alpha: float = 1.0,
31+
title: Optional[str] = None,
32+
xlabel: Optional[str] = None,
33+
ylabel: Optional[str] = None,
34+
sort_data: bool = True,
35+
**kwargs,
36+
) -> "Figure":
37+
"""
38+
Create a basic line plot visualizing trends over a continuous or sequential axis.
39+
40+
Args:
41+
data: Input DataFrame with required columns
42+
x: Column name for x-axis values
43+
y: Column name for y-axis values
44+
figsize: Figure size as (width, height) tuple (default: (16, 9))
45+
color: Line color (default: "steelblue")
46+
linewidth: Width of the line (default: 2.0)
47+
linestyle: Line style, e.g., '-', '--', '-.', ':' (default: '-')
48+
marker: Marker style for data points (default: None)
49+
markersize: Size of markers (default: 6)
50+
alpha: Transparency level (default: 1.0)
51+
title: Plot title (default: None)
52+
xlabel: X-axis label (default: uses column name)
53+
ylabel: Y-axis label (default: uses column name)
54+
sort_data: Whether to sort data by x-axis values (default: True)
55+
**kwargs: Additional parameters passed to seaborn lineplot function
56+
57+
Returns:
58+
Matplotlib Figure object
59+
60+
Raises:
61+
ValueError: If data is empty
62+
KeyError: If required columns not found
63+
TypeError: If y column contains non-numeric data
64+
65+
Example:
66+
>>> data = pd.DataFrame({'time': [1, 2, 3], 'value': [2, 4, 3]})
67+
>>> fig = create_plot(data, 'time', 'value')
68+
"""
69+
# Input validation
70+
if data.empty:
71+
raise ValueError("Data cannot be empty")
72+
73+
# Check required columns
74+
for col in [x, y]:
75+
if col not in data.columns:
76+
available = ", ".join(data.columns)
77+
raise KeyError(f"Column '{col}' not found. Available columns: {available}")
78+
79+
# Check if y column is numeric
80+
if not pd.api.types.is_numeric_dtype(data[y]):
81+
raise TypeError(f"Column '{y}' must contain numeric data")
82+
83+
# Create a copy to avoid modifying original data
84+
plot_data = data.copy()
85+
86+
# Sort data by x-axis for proper line rendering
87+
if sort_data:
88+
plot_data = plot_data.sort_values(by=x).reset_index(drop=True)
89+
90+
# Create figure
91+
fig, ax = plt.subplots(figsize=figsize)
92+
93+
# Set seaborn style for clean appearance
94+
sns.set_style("whitegrid")
95+
96+
# Plot data using seaborn lineplot
97+
sns.lineplot(
98+
data=plot_data,
99+
x=x,
100+
y=y,
101+
color=color,
102+
linewidth=linewidth,
103+
linestyle=linestyle,
104+
marker=marker,
105+
markersize=markersize,
106+
alpha=alpha,
107+
ax=ax,
108+
**kwargs,
109+
)
110+
111+
# Labels and title
112+
ax.set_xlabel(xlabel or x)
113+
ax.set_ylabel(ylabel or y)
114+
115+
if title:
116+
ax.set_title(title)
117+
118+
# Apply styling - make grid subtle
119+
ax.grid(True, alpha=0.3)
120+
121+
# Reset seaborn style to avoid affecting other plots
122+
sns.set_style("ticks")
123+
124+
# Layout
125+
plt.tight_layout()
126+
127+
return fig
128+
129+
130+
if __name__ == "__main__":
131+
# Sample data for testing - time series data
132+
np.random.seed(42)
133+
n_points = 50
134+
135+
# Generate time series data with trend and noise
136+
time = np.arange(n_points)
137+
values = 10 + 0.5 * time + np.random.randn(n_points) * 2
138+
139+
data = pd.DataFrame({"time": time, "value": values})
140+
141+
# Create plot
142+
fig = create_plot(
143+
data, "time", "value", title="Basic Line Plot Example", xlabel="Time", ylabel="Value", marker="o", markersize=4
144+
)
145+
146+
# Save for inspection - ALWAYS use 'plot.png' as filename
147+
plt.savefig("plot.png", dpi=300, bbox_inches="tight")
148+
print("Plot saved to plot.png")

specs/line-basic.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# line-basic: Basic Line Plot
2+
3+
A fundamental line plot that visualizes trends and changes in data over a continuous or sequential axis, commonly used for time series and ordered data.
4+
5+
## Data Requirements
6+
7+
- **x**: Column for x-axis values (numeric, datetime, or ordered categorical)
8+
- **y**: Numeric column for y-axis values
9+
10+
## Optional Parameters
11+
12+
- `figsize`: Figure size as (width, height) tuple (default: (16, 9))
13+
- `color`: Line color (default: "steelblue")
14+
- `linewidth`: Width of the line (default: 2.0)
15+
- `linestyle`: Line style, e.g., '-', '--', '-.', ':' (default: '-')
16+
- `marker`: Marker style for data points (default: None)
17+
- `markersize`: Size of markers (default: 6)
18+
- `alpha`: Transparency level (default: 1.0)
19+
- `title`: Plot title (default: None)
20+
- `xlabel`: X-axis label (default: uses column name)
21+
- `ylabel`: Y-axis label (default: uses column name)
22+
23+
## Expected Output
24+
25+
A line plot with:
26+
- X and Y axes labeled with column names (or custom labels)
27+
- Smooth, continuous line connecting data points
28+
- Grid visible but subtle (alpha ≤ 0.3)
29+
- Professional appearance with proper spacing
30+
- Optional markers at data points for clarity
31+
32+
## Quality Criteria
33+
34+
- [x] Axes labeled clearly
35+
- [x] Grid visible but subtle
36+
- [x] Line clearly visible with appropriate width
37+
- [x] No overlapping labels
38+
- [x] Appropriate figure size (16:9 aspect ratio)
39+
- [x] Type hints and validation present
40+
- [x] Data sorted by x-axis for proper line rendering
41+
42+
## Examples
43+
44+
### Example 1: Basic Usage
45+
```python
46+
import pandas as pd
47+
data = pd.DataFrame({
48+
'time': [1, 2, 3, 4, 5],
49+
'value': [2, 4, 3, 5, 6]
50+
})
51+
fig = create_plot(data, 'time', 'value')
52+
```
53+
54+
### Example 2: Custom Styling
55+
```python
56+
fig = create_plot(
57+
data,
58+
'time',
59+
'value',
60+
color='darkblue',
61+
linewidth=2.5,
62+
marker='o',
63+
title='Trend Analysis'
64+
)
65+
```
66+
67+
## Implementation Notes
68+
69+
- Data should be sorted by x-axis values for proper line rendering
70+
- Handle missing/NaN values gracefully
71+
- Validate that y column contains numeric data
72+
- X-axis can be numeric, datetime, or ordered categorical
73+
74+
## Tags
75+
76+
line, trend, time-series, basic, 2d
77+
78+
## Use Cases
79+
80+
- Time series visualization of stock prices
81+
- Tracking metrics over time (e.g., website traffic)
82+
- Displaying trends in scientific measurements
83+
- Monitoring system performance metrics
84+
- Visualizing growth or decline patterns

0 commit comments

Comments
 (0)