Skip to content

Commit 89e5d35

Browse files
feat(matplotlib): implement bar-basic (#126)
## Summary Implements `bar-basic` for **matplotlib** library. **Parent Issue:** #117 **Sub-Issue:** #118 **Base Branch:** `plot/bar-basic` **Attempt:** 1/3 ## Implementation - `plots/matplotlib/bar/bar-basic/default.py` ## Features - Vertical bar chart with customizable colors and transparency - Axis labels with sensible defaults (uses column names when not specified) - Subtle y-axis grid (alpha=0.3) for readability - Rotatable x-axis labels for long category names - Y-axis always starts at zero for accurate visual comparison - Full input validation with descriptive error messages - Google-style docstrings with type hints Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
1 parent 2dad82e commit 89e5d35

1 file changed

Lines changed: 114 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)