Skip to content

Commit eabafca

Browse files
feat(seaborn): implement bar-basic (#127)
## Summary Implements `bar-basic` for **seaborn** library. **Parent Issue:** #117 **Sub-Issue:** #119 **Base Branch:** `plot/bar-basic` **Attempt:** 1/3 ## Implementation - `plots/seaborn/barplot/bar-basic/default.py` ## Features - Basic vertical bar chart using `sns.barplot()` - Full input validation with descriptive error messages - Configurable styling: color, edgecolor, alpha - Custom axis labels and title support - X-axis label rotation for long category names - Subtle y-axis grid (alpha=0.3) for readability - Y-axis starts at zero for accurate visual comparison - Google-style docstring with Args, Returns, Raises, Example - Type hints throughout Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
1 parent 66515b1 commit eabafca

1 file changed

Lines changed: 116 additions & 0 deletions

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""
2+
bar-basic: Basic Bar Chart
3+
Library: seaborn
4+
"""
5+
6+
from typing import TYPE_CHECKING
7+
8+
import matplotlib.pyplot as plt
9+
import pandas as pd
10+
import seaborn as sns
11+
12+
13+
if TYPE_CHECKING:
14+
from matplotlib.figure import Figure
15+
16+
17+
def create_plot(
18+
data: pd.DataFrame,
19+
category: str,
20+
value: str,
21+
figsize: tuple[float, float] = (10, 6),
22+
color: str = "steelblue",
23+
edgecolor: str = "black",
24+
alpha: float = 0.8,
25+
title: str | None = None,
26+
xlabel: str | None = None,
27+
ylabel: str | None = None,
28+
rotation: int = 0,
29+
**kwargs,
30+
) -> "Figure":
31+
"""
32+
Create a basic vertical bar chart for categorical data comparison.
33+
34+
A fundamental bar chart displaying rectangular bars with heights proportional
35+
to their numeric values, ideal for comparing quantities across categories.
36+
37+
Args:
38+
data: Input DataFrame containing the data to plot
39+
category: Column name for category labels (x-axis)
40+
value: Column name for numeric values (bar heights)
41+
figsize: Figure size as (width, height) in inches
42+
color: Bar fill color
43+
edgecolor: Bar edge color
44+
alpha: Transparency level for bars (0-1)
45+
title: Plot title (optional)
46+
xlabel: X-axis label (defaults to column name if None)
47+
ylabel: Y-axis label (defaults to column name if None)
48+
rotation: Rotation angle for x-axis labels in degrees
49+
**kwargs: Additional parameters passed to seaborn.barplot
50+
51+
Returns:
52+
Matplotlib Figure object
53+
54+
Raises:
55+
ValueError: If data is empty
56+
KeyError: If required columns not found in data
57+
58+
Example:
59+
>>> data = pd.DataFrame({
60+
... 'category': ['A', 'B', 'C'],
61+
... 'value': [10, 20, 15]
62+
... })
63+
>>> fig = create_plot(data, 'category', 'value', title='Sample Chart')
64+
"""
65+
# Input validation
66+
if data.empty:
67+
raise ValueError("Data cannot be empty")
68+
69+
for col in [category, value]:
70+
if col not in data.columns:
71+
available = ", ".join(data.columns)
72+
raise KeyError(f"Column '{col}' not found. Available: {available}")
73+
74+
# Create figure
75+
fig, ax = plt.subplots(figsize=figsize)
76+
77+
# Plot data using seaborn barplot
78+
sns.barplot(data=data, x=category, y=value, color=color, edgecolor=edgecolor, alpha=alpha, ax=ax, **kwargs)
79+
80+
# Set y-axis to start at zero for accurate visual comparison
81+
ax.set_ylim(bottom=0)
82+
83+
# Add subtle grid on y-axis only
84+
ax.yaxis.grid(True, alpha=0.3)
85+
ax.set_axisbelow(True)
86+
87+
# Labels
88+
ax.set_xlabel(xlabel if xlabel is not None else category)
89+
ax.set_ylabel(ylabel if ylabel is not None else value)
90+
91+
# Title
92+
if title is not None:
93+
ax.set_title(title)
94+
95+
# Rotate x-axis labels if specified
96+
if rotation != 0:
97+
plt.xticks(rotation=rotation, ha="right")
98+
99+
# Layout
100+
plt.tight_layout()
101+
102+
return fig
103+
104+
105+
if __name__ == "__main__":
106+
# Sample data for testing
107+
sample_data = pd.DataFrame(
108+
{"category": ["Product A", "Product B", "Product C", "Product D", "Product E"], "value": [45, 78, 52, 91, 63]}
109+
)
110+
111+
# Create plot
112+
fig = create_plot(sample_data, "category", "value", title="Sales by Product", xlabel="Product", ylabel="Sales ($)")
113+
114+
# Save - ALWAYS use 'plot.png'!
115+
plt.savefig("plot.png", dpi=300, bbox_inches="tight")
116+
print("Plot saved to plot.png")

0 commit comments

Comments
 (0)