|
| 1 | +""" |
| 2 | +line-basic: Basic Line Chart |
| 3 | +Implementation for: matplotlib |
| 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 | + |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from matplotlib.figure import Figure |
| 17 | + |
| 18 | + |
| 19 | +def create_plot( |
| 20 | + data: pd.DataFrame, |
| 21 | + x: str, |
| 22 | + y: str, |
| 23 | + figsize: tuple[float, float] = (16, 9), |
| 24 | + color: str = "steelblue", |
| 25 | + linewidth: float = 2.0, |
| 26 | + marker: Optional[str] = "o", |
| 27 | + markersize: float = 6, |
| 28 | + alpha: float = 0.8, |
| 29 | + title: Optional[str] = None, |
| 30 | + xlabel: Optional[str] = None, |
| 31 | + ylabel: Optional[str] = None, |
| 32 | + linestyle: str = "-", |
| 33 | + **kwargs, |
| 34 | +) -> "Figure": |
| 35 | + """ |
| 36 | + Create a basic line chart visualizing the trend of data points. |
| 37 | +
|
| 38 | + Args: |
| 39 | + data: Input DataFrame with required columns |
| 40 | + x: Column name for x-axis values |
| 41 | + y: Column name for y-axis values |
| 42 | + figsize: Figure size as (width, height) tuple (default: (16, 9)) |
| 43 | + color: Line color (default: "steelblue") |
| 44 | + linewidth: Width of the line (default: 2.0) |
| 45 | + marker: Marker style for data points (default: "o") |
| 46 | + markersize: Size of markers (default: 6) |
| 47 | + alpha: Transparency level (default: 0.8) |
| 48 | + title: Plot title (default: None) |
| 49 | + xlabel: X-axis label (default: uses column name) |
| 50 | + ylabel: Y-axis label (default: uses column name) |
| 51 | + linestyle: Line style (default: "-" solid) |
| 52 | + **kwargs: Additional parameters passed to plot function |
| 53 | +
|
| 54 | + Returns: |
| 55 | + Matplotlib Figure object |
| 56 | +
|
| 57 | + Raises: |
| 58 | + ValueError: If data is empty |
| 59 | + KeyError: If required columns not found |
| 60 | + TypeError: If y column contains non-numeric data |
| 61 | +
|
| 62 | + Example: |
| 63 | + >>> data = pd.DataFrame({'month': [1, 2, 3], 'sales': [100, 150, 130]}) |
| 64 | + >>> fig = create_plot(data, 'month', 'sales') |
| 65 | + """ |
| 66 | + # Input validation |
| 67 | + if data.empty: |
| 68 | + raise ValueError("Data cannot be empty") |
| 69 | + |
| 70 | + # Check required columns |
| 71 | + for col in [x, y]: |
| 72 | + if col not in data.columns: |
| 73 | + available = ", ".join(data.columns) |
| 74 | + raise KeyError(f"Column '{col}' not found. Available columns: {available}") |
| 75 | + |
| 76 | + # Check if y column is numeric |
| 77 | + if not pd.api.types.is_numeric_dtype(data[y]): |
| 78 | + raise TypeError(f"Column '{y}' must contain numeric data") |
| 79 | + |
| 80 | + # Create figure |
| 81 | + fig, ax = plt.subplots(figsize=figsize) |
| 82 | + |
| 83 | + # Plot data |
| 84 | + ax.plot( |
| 85 | + data[x], |
| 86 | + data[y], |
| 87 | + color=color, |
| 88 | + linewidth=linewidth, |
| 89 | + marker=marker, |
| 90 | + markersize=markersize, |
| 91 | + alpha=alpha, |
| 92 | + linestyle=linestyle, |
| 93 | + **kwargs, |
| 94 | + ) |
| 95 | + |
| 96 | + # Labels and title |
| 97 | + ax.set_xlabel(xlabel or x) |
| 98 | + ax.set_ylabel(ylabel or y) |
| 99 | + |
| 100 | + if title: |
| 101 | + ax.set_title(title) |
| 102 | + |
| 103 | + # Apply styling |
| 104 | + ax.grid(True, alpha=0.3) |
| 105 | + |
| 106 | + # Layout |
| 107 | + plt.tight_layout() |
| 108 | + |
| 109 | + return fig |
| 110 | + |
| 111 | + |
| 112 | +if __name__ == "__main__": |
| 113 | + # Sample data for testing - monthly sales data |
| 114 | + np.random.seed(42) |
| 115 | + |
| 116 | + months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] |
| 117 | + base_values = [100, 120, 115, 130, 145, 160, 155, 170, 180, 175, 190, 210] |
| 118 | + noise = np.random.randn(12) * 5 |
| 119 | + |
| 120 | + data = pd.DataFrame({"month": months, "sales": [base + n for base, n in zip(base_values, noise, strict=True)]}) |
| 121 | + |
| 122 | + # Create plot |
| 123 | + fig = create_plot(data, "month", "sales", title="Monthly Sales Trend", xlabel="Month", ylabel="Sales ($)") |
| 124 | + |
| 125 | + # Save for inspection - ALWAYS use 'plot.png' as filename |
| 126 | + plt.savefig("plot.png", dpi=300, bbox_inches="tight") |
| 127 | + print("Plot saved to plot.png") |
0 commit comments