|
| 1 | +""" |
| 2 | +line-basic: Basic Line Plot |
| 3 | +Implementation for: seaborn |
| 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 | +import seaborn as sns |
| 14 | + |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from matplotlib.figure import Figure |
| 18 | + |
| 19 | + |
| 20 | +def create_plot( |
| 21 | + data: pd.DataFrame, |
| 22 | + x: str, |
| 23 | + y: str, |
| 24 | + figsize: tuple[float, float] = (16, 9), |
| 25 | + color: str = "steelblue", |
| 26 | + linewidth: float = 2.0, |
| 27 | + linestyle: str = "-", |
| 28 | + marker: Optional[str] = None, |
| 29 | + markersize: float = 6, |
| 30 | + alpha: float = 1.0, |
| 31 | + title: Optional[str] = None, |
| 32 | + xlabel: Optional[str] = None, |
| 33 | + ylabel: Optional[str] = None, |
| 34 | + sort_data: bool = True, |
| 35 | + **kwargs, |
| 36 | +) -> "Figure": |
| 37 | + """ |
| 38 | + Create a basic line plot visualizing trends over a continuous or sequential axis. |
| 39 | +
|
| 40 | + Args: |
| 41 | + data: Input DataFrame with required columns |
| 42 | + x: Column name for x-axis values |
| 43 | + y: Column name for y-axis values |
| 44 | + figsize: Figure size as (width, height) tuple (default: (16, 9)) |
| 45 | + color: Line color (default: "steelblue") |
| 46 | + linewidth: Width of the line (default: 2.0) |
| 47 | + linestyle: Line style, e.g., '-', '--', '-.', ':' (default: '-') |
| 48 | + marker: Marker style for data points (default: None) |
| 49 | + markersize: Size of markers (default: 6) |
| 50 | + alpha: Transparency level (default: 1.0) |
| 51 | + title: Plot title (default: None) |
| 52 | + xlabel: X-axis label (default: uses column name) |
| 53 | + ylabel: Y-axis label (default: uses column name) |
| 54 | + sort_data: Whether to sort data by x-axis values (default: True) |
| 55 | + **kwargs: Additional parameters passed to seaborn lineplot function |
| 56 | +
|
| 57 | + Returns: |
| 58 | + Matplotlib Figure object |
| 59 | +
|
| 60 | + Raises: |
| 61 | + ValueError: If data is empty |
| 62 | + KeyError: If required columns not found |
| 63 | + TypeError: If y column contains non-numeric data |
| 64 | +
|
| 65 | + Example: |
| 66 | + >>> data = pd.DataFrame({'time': [1, 2, 3], 'value': [2, 4, 3]}) |
| 67 | + >>> fig = create_plot(data, 'time', 'value') |
| 68 | + """ |
| 69 | + # Input validation |
| 70 | + if data.empty: |
| 71 | + raise ValueError("Data cannot be empty") |
| 72 | + |
| 73 | + # Check required columns |
| 74 | + for col in [x, y]: |
| 75 | + if col not in data.columns: |
| 76 | + available = ", ".join(data.columns) |
| 77 | + raise KeyError(f"Column '{col}' not found. Available columns: {available}") |
| 78 | + |
| 79 | + # Check if y column is numeric |
| 80 | + if not pd.api.types.is_numeric_dtype(data[y]): |
| 81 | + raise TypeError(f"Column '{y}' must contain numeric data") |
| 82 | + |
| 83 | + # Create a copy to avoid modifying original data |
| 84 | + plot_data = data.copy() |
| 85 | + |
| 86 | + # Sort data by x-axis for proper line rendering |
| 87 | + if sort_data: |
| 88 | + plot_data = plot_data.sort_values(by=x).reset_index(drop=True) |
| 89 | + |
| 90 | + # Create figure |
| 91 | + fig, ax = plt.subplots(figsize=figsize) |
| 92 | + |
| 93 | + # Set seaborn style for clean appearance |
| 94 | + sns.set_style("whitegrid") |
| 95 | + |
| 96 | + # Plot data using seaborn lineplot |
| 97 | + sns.lineplot( |
| 98 | + data=plot_data, |
| 99 | + x=x, |
| 100 | + y=y, |
| 101 | + color=color, |
| 102 | + linewidth=linewidth, |
| 103 | + linestyle=linestyle, |
| 104 | + marker=marker, |
| 105 | + markersize=markersize, |
| 106 | + alpha=alpha, |
| 107 | + ax=ax, |
| 108 | + **kwargs, |
| 109 | + ) |
| 110 | + |
| 111 | + # Labels and title |
| 112 | + ax.set_xlabel(xlabel or x) |
| 113 | + ax.set_ylabel(ylabel or y) |
| 114 | + |
| 115 | + if title: |
| 116 | + ax.set_title(title) |
| 117 | + |
| 118 | + # Apply styling - make grid subtle |
| 119 | + ax.grid(True, alpha=0.3) |
| 120 | + |
| 121 | + # Reset seaborn style to avoid affecting other plots |
| 122 | + sns.set_style("ticks") |
| 123 | + |
| 124 | + # Layout |
| 125 | + plt.tight_layout() |
| 126 | + |
| 127 | + return fig |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + # Sample data for testing - time series data |
| 132 | + np.random.seed(42) |
| 133 | + n_points = 50 |
| 134 | + |
| 135 | + # Generate time series data with trend and noise |
| 136 | + time = np.arange(n_points) |
| 137 | + values = 10 + 0.5 * time + np.random.randn(n_points) * 2 |
| 138 | + |
| 139 | + data = pd.DataFrame({"time": time, "value": values}) |
| 140 | + |
| 141 | + # Create plot |
| 142 | + fig = create_plot( |
| 143 | + data, "time", "value", title="Basic Line Plot Example", xlabel="Time", ylabel="Value", marker="o", markersize=4 |
| 144 | + ) |
| 145 | + |
| 146 | + # Save for inspection - ALWAYS use 'plot.png' as filename |
| 147 | + plt.savefig("plot.png", dpi=300, bbox_inches="tight") |
| 148 | + print("Plot saved to plot.png") |
0 commit comments