|
| 1 | +""" |
| 2 | +area-basic: Basic Area Chart |
| 3 | +Implementation for: altair |
| 4 | +Variant: default |
| 5 | +Python: 3.10+ |
| 6 | +""" |
| 7 | + |
| 8 | +from typing import TYPE_CHECKING, Optional |
| 9 | + |
| 10 | +import altair as alt |
| 11 | +import pandas as pd |
| 12 | + |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from altair import LayerChart |
| 16 | + |
| 17 | + |
| 18 | +def create_plot( |
| 19 | + data: pd.DataFrame, |
| 20 | + x: str, |
| 21 | + y: str, |
| 22 | + title: Optional[str] = None, |
| 23 | + xlabel: Optional[str] = None, |
| 24 | + ylabel: Optional[str] = None, |
| 25 | + color: str = "steelblue", |
| 26 | + alpha: float = 0.7, |
| 27 | + line_color: Optional[str] = None, |
| 28 | + line_width: float = 2, |
| 29 | + show_line: bool = True, |
| 30 | + width: int = 800, |
| 31 | + height: int = 450, |
| 32 | + **kwargs, |
| 33 | +) -> "LayerChart": |
| 34 | + """ |
| 35 | + Create a basic filled area chart showing a single data series using altair. |
| 36 | +
|
| 37 | + Args: |
| 38 | + data: Input DataFrame with required columns |
| 39 | + x: Column name for x-axis values (numeric or datetime) |
| 40 | + y: Column name for y-axis values (numeric) |
| 41 | + title: Plot title (optional) |
| 42 | + xlabel: Custom x-axis label (optional, defaults to x column name) |
| 43 | + ylabel: Custom y-axis label (optional, defaults to y column name) |
| 44 | + color: Fill color for the area (default: 'steelblue') |
| 45 | + alpha: Transparency level for the fill (default: 0.7) |
| 46 | + line_color: Color of the line at the top (default: same as fill color) |
| 47 | + line_width: Width of the top line (default: 2) |
| 48 | + show_line: Whether to show the line at the top (default: True) |
| 49 | + width: Figure width in pixels (default: 800) |
| 50 | + height: Figure height in pixels (default: 450) |
| 51 | + **kwargs: Additional parameters for altair chart configuration |
| 52 | +
|
| 53 | + Returns: |
| 54 | + Altair LayerChart object |
| 55 | +
|
| 56 | + Raises: |
| 57 | + ValueError: If data is empty |
| 58 | + KeyError: If required columns not found |
| 59 | +
|
| 60 | + Example: |
| 61 | + >>> data = pd.DataFrame({ |
| 62 | + ... 'month': [1, 2, 3, 4, 5, 6], |
| 63 | + ... 'sales': [100, 150, 200, 180, 220, 250] |
| 64 | + ... }) |
| 65 | + >>> chart = create_plot(data, x='month', y='sales') |
| 66 | + """ |
| 67 | + # Input validation |
| 68 | + if data.empty: |
| 69 | + raise ValueError("Data cannot be empty") |
| 70 | + |
| 71 | + # Check required columns |
| 72 | + for col in [x, y]: |
| 73 | + if col not in data.columns: |
| 74 | + available = ", ".join(data.columns) |
| 75 | + raise KeyError(f"Column '{col}' not found. Available columns: {available}") |
| 76 | + |
| 77 | + # Determine encoding type for x-axis |
| 78 | + x_dtype = data[x].dtype |
| 79 | + if pd.api.types.is_datetime64_any_dtype(x_dtype): |
| 80 | + x_encoding = f"{x}:T" |
| 81 | + elif pd.api.types.is_numeric_dtype(x_dtype): |
| 82 | + x_encoding = f"{x}:Q" |
| 83 | + else: |
| 84 | + x_encoding = f"{x}:O" |
| 85 | + |
| 86 | + # Use provided line_color or default to fill color |
| 87 | + actual_line_color = line_color if line_color is not None else color |
| 88 | + |
| 89 | + # Create the area chart |
| 90 | + area = ( |
| 91 | + alt.Chart(data) |
| 92 | + .mark_area( |
| 93 | + color=color, |
| 94 | + opacity=alpha, |
| 95 | + line={"color": actual_line_color, "strokeWidth": line_width} if show_line else False, |
| 96 | + ) |
| 97 | + .encode( |
| 98 | + x=alt.X( |
| 99 | + x_encoding, |
| 100 | + title=xlabel or x, |
| 101 | + axis=alt.Axis(labelAngle=0 if len(data) <= 12 else -45, labelLimit=200), |
| 102 | + ), |
| 103 | + y=alt.Y( |
| 104 | + f"{y}:Q", |
| 105 | + title=ylabel or y, |
| 106 | + scale=alt.Scale(domain=[0, data[y].max() * 1.1]), |
| 107 | + ), |
| 108 | + tooltip=[ |
| 109 | + alt.Tooltip(x_encoding, title=xlabel or x), |
| 110 | + alt.Tooltip(f"{y}:Q", title=ylabel or y, format=",.2f"), |
| 111 | + ], |
| 112 | + ) |
| 113 | + ) |
| 114 | + |
| 115 | + # Configure the chart with title and styling |
| 116 | + chart = area.properties( |
| 117 | + width=width, |
| 118 | + height=height, |
| 119 | + title=alt.TitleParams( |
| 120 | + text=title or "Area Chart", |
| 121 | + fontSize=16, |
| 122 | + anchor="middle", |
| 123 | + ), |
| 124 | + ).configure_view( |
| 125 | + strokeWidth=0, |
| 126 | + ).configure_axis( |
| 127 | + grid=True, |
| 128 | + gridOpacity=0.3, |
| 129 | + gridDash=[3, 3], |
| 130 | + domainWidth=1, |
| 131 | + tickWidth=1, |
| 132 | + ) |
| 133 | + |
| 134 | + return chart |
| 135 | + |
| 136 | + |
| 137 | +if __name__ == "__main__": |
| 138 | + # Sample data for testing - monthly sales data |
| 139 | + sample_data = pd.DataFrame({ |
| 140 | + "Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], |
| 141 | + "Sales": [120, 150, 180, 165, 200, 230, 250, 245, 220, 195, 170, 210], |
| 142 | + }) |
| 143 | + |
| 144 | + # Create plot with ordinal x-axis |
| 145 | + chart = create_plot( |
| 146 | + sample_data, |
| 147 | + x="Month", |
| 148 | + y="Sales", |
| 149 | + title="Monthly Sales Trend", |
| 150 | + xlabel="Month", |
| 151 | + ylabel="Sales ($K)", |
| 152 | + color="steelblue", |
| 153 | + alpha=0.7, |
| 154 | + ) |
| 155 | + |
| 156 | + # Save as PNG |
| 157 | + chart.save("plot.png", scale_factor=2.0) |
| 158 | + print("Plot saved to plot.png") |
0 commit comments