Skip to content

Commit fa71ad0

Browse files
feat(plotly): implement bar-basic (#130)
## Summary Implements `bar-basic` for **plotly** library. **Parent Issue:** #117 **Sub-Issue:** #120 **Base Branch:** `plot/bar-basic` **Attempt:** 1/3 ## Implementation - `plots/plotly/bar/bar-basic/default.py` ## Features - Basic vertical bar chart for categorical data comparison - Customizable bar colors, edge colors, and transparency - Configurable axis labels and title - Y-axis starts at zero for accurate visual comparison - Subtle grid lines (alpha=0.3) for readability - Support for x-axis label rotation for long category names - 16:9 aspect ratio (1600x900 pixels) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
1 parent 44056e6 commit fa71ad0

1 file changed

Lines changed: 125 additions & 0 deletions

File tree

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
"""
2+
bar-basic: Basic Bar Chart
3+
Library: plotly
4+
"""
5+
6+
from typing import TYPE_CHECKING
7+
8+
import pandas as pd
9+
import plotly.graph_objects as go
10+
11+
12+
if TYPE_CHECKING:
13+
pass
14+
15+
16+
def create_plot(
17+
data: pd.DataFrame,
18+
category: str,
19+
value: str,
20+
figsize: tuple[int, int] = (1600, 900),
21+
color: str = "steelblue",
22+
edgecolor: str = "black",
23+
alpha: float = 0.8,
24+
title: str | None = None,
25+
xlabel: str | None = None,
26+
ylabel: str | None = None,
27+
rotation: int = 0,
28+
**kwargs,
29+
) -> go.Figure:
30+
"""
31+
Create a basic vertical bar chart for categorical data comparison.
32+
33+
A fundamental bar chart that displays rectangular bars with heights
34+
proportional to the values they represent. Each bar corresponds to
35+
a category, making it ideal for comparing quantities across discrete
36+
categories.
37+
38+
Args:
39+
data: Input DataFrame containing the data to plot.
40+
category: Column name for category labels (x-axis).
41+
value: Column name for numeric values (bar heights).
42+
figsize: Figure size as (width, height) in pixels. Defaults to (1600, 900).
43+
color: Bar fill color. Defaults to "steelblue".
44+
edgecolor: Bar edge/outline color. Defaults to "black".
45+
alpha: Transparency level for bars (0-1). Defaults to 0.8.
46+
title: Plot title. Defaults to None.
47+
xlabel: X-axis label. Defaults to column name if None.
48+
ylabel: Y-axis label. Defaults to column name if None.
49+
rotation: Rotation angle for x-axis labels in degrees. Defaults to 0.
50+
**kwargs: Additional parameters passed to go.Bar.
51+
52+
Returns:
53+
Plotly Figure object containing the bar chart.
54+
55+
Raises:
56+
ValueError: If data is empty.
57+
KeyError: If required columns are not found in data.
58+
59+
Example:
60+
>>> data = pd.DataFrame({
61+
... 'category': ['A', 'B', 'C', 'D'],
62+
... 'value': [45, 78, 52, 91]
63+
... })
64+
>>> fig = create_plot(data, 'category', 'value', title='Sales by Product')
65+
"""
66+
# Input validation
67+
if data.empty:
68+
raise ValueError("Data cannot be empty")
69+
70+
for col in [category, value]:
71+
if col not in data.columns:
72+
available = ", ".join(data.columns)
73+
raise KeyError(f"Column '{col}' not found. Available: {available}")
74+
75+
# Set default labels from column names
76+
x_label = xlabel if xlabel is not None else category
77+
y_label = ylabel if ylabel is not None else value
78+
79+
# Create figure
80+
fig = go.Figure()
81+
82+
# Add bar trace
83+
fig.add_trace(
84+
go.Bar(
85+
x=data[category],
86+
y=data[value],
87+
marker=dict(color=color, opacity=alpha, line=dict(color=edgecolor, width=1)),
88+
**kwargs,
89+
)
90+
)
91+
92+
# Update layout with styling
93+
fig.update_layout(
94+
title=dict(text=title, x=0.5, xanchor="center") if title else None,
95+
xaxis=dict(title=dict(text=x_label, font=dict(size=14)), tickangle=-rotation, tickfont=dict(size=12)),
96+
yaxis=dict(
97+
title=dict(text=y_label, font=dict(size=14)),
98+
tickfont=dict(size=12),
99+
rangemode="tozero",
100+
showgrid=True,
101+
gridwidth=1,
102+
gridcolor="rgba(128, 128, 128, 0.3)",
103+
),
104+
template="plotly_white",
105+
width=figsize[0],
106+
height=figsize[1],
107+
showlegend=False,
108+
margin=dict(l=80, r=40, t=80 if title else 40, b=80),
109+
)
110+
111+
return fig
112+
113+
114+
if __name__ == "__main__":
115+
# Sample data for testing
116+
sample_data = pd.DataFrame(
117+
{"category": ["Product A", "Product B", "Product C", "Product D", "Product E"], "value": [45, 78, 52, 91, 63]}
118+
)
119+
120+
# Create plot
121+
fig = create_plot(sample_data, "category", "value", title="Sales by Product")
122+
123+
# Save
124+
fig.write_image("plot.png", width=1600, height=900, scale=2)
125+
print("Plot saved to plot.png")

0 commit comments

Comments
 (0)