-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquick_plot.py
More file actions
214 lines (172 loc) Β· 6.29 KB
/
quick_plot.py
File metadata and controls
214 lines (172 loc) Β· 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python3
"""
Create quick plots from CSV/JSON data files.
Usage:
python quick_plot.py <data_file> [--type TYPE] [--x X] [--y Y] [--output OUTPUT]
"""
import sys
from pathlib import Path
# Ensure codomyrmex is in path
try:
import codomyrmex
except ImportError:
project_root = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(project_root / "src"))
import argparse
import csv
import json
def load_data(file_path: str) -> tuple:
"""Load data from CSV or JSON file. Returns (headers, rows)."""
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
suffix = path.suffix.lower()
if suffix == ".csv":
with open(path) as f:
reader = csv.DictReader(f)
rows = list(reader)
if not rows:
return [], []
headers = list(rows[0].keys())
return headers, rows
elif suffix == ".json":
with open(path) as f:
data = json.load(f)
if isinstance(data, list) and data:
headers = list(data[0].keys())
return headers, data
raise ValueError("JSON must be an array of objects")
else:
raise ValueError(f"Unsupported file format: {suffix}")
def create_text_plot(
data: list,
x_col: str,
y_col: str,
plot_type: str,
width: int = 60,
height: int = 15,
) -> str:
"""Create a simple ASCII visualization."""
x_values = [row.get(x_col, "") for row in data]
y_values = []
for row in data:
try:
y_values.append(float(row.get(y_col, 0)))
except (ValueError, TypeError):
y_values.append(0)
if not y_values:
return "No data to plot"
max_y = max(y_values) if max(y_values) > 0 else 1
min_y = min(y_values)
y_range = max_y - min_y if max_y != min_y else 1
output = []
output.append(f"\nπ {plot_type.upper()} Plot: {y_col} by {x_col}\n")
output.append(f" Max: {max_y:.2f}")
if plot_type == "bar":
# Horizontal bar chart
max_label_len = min(15, max(len(str(x)) for x in x_values))
bar_width = width - max_label_len - 10
for x, y in zip(x_values, y_values, strict=False):
bar_len = int((y - min_y) / y_range * bar_width) if y_range > 0 else 0
bar = "β" * bar_len
label = str(x)[:max_label_len].ljust(max_label_len)
output.append(f" {label} β{bar} {y:.1f}")
elif plot_type == "line":
# ASCII line chart
chart = [[" " for _ in range(len(y_values))] for _ in range(height)]
for i, y in enumerate(y_values):
row = (
int((1 - (y - min_y) / y_range) * (height - 1))
if y_range > 0
else height // 2
)
row = max(0, min(height - 1, row))
chart[row][i] = "β"
for row_idx, row in enumerate(chart):
y_label = f"{max_y - (row_idx / (height - 1)) * y_range:.1f}".rjust(8)
output.append(f"{y_label} β{''.join(row)}")
output.append(" " * 9 + "β" + "β" * len(y_values))
elif plot_type == "scatter":
# ASCII scatter plot
chart = [[" " for _ in range(width)] for _ in range(height)]
try:
x_nums = [float(x) for x in x_values]
x_min, x_max = min(x_nums), max(x_nums)
x_range = x_max - x_min if x_max != x_min else 1
for x, y in zip(x_nums, y_values, strict=False):
col = (
int((x - x_min) / x_range * (width - 1))
if x_range > 0
else width // 2
)
row = (
int((1 - (y - min_y) / y_range) * (height - 1))
if y_range > 0
else height // 2
)
col = max(0, min(width - 1, col))
row = max(0, min(height - 1, row))
chart[row][col] = "β"
for row in chart:
output.append(" β" + "".join(row))
output.append(" β" + "β" * width)
except ValueError:
output.append(" (Scatter requires numeric X values)")
output.append(f"\n Data points: {len(data)}")
return "\n".join(output)
def main():
# Auto-injected: Load configuration
from pathlib import Path
import yaml
config_path = (
Path(__file__).resolve().parent.parent.parent
/ "config"
/ "data_visualization"
/ "config.yaml"
)
if config_path.exists():
with open(config_path) as f:
yaml.safe_load(f) or {}
print("Loaded config from config/data_visualization/config.yaml")
parser = argparse.ArgumentParser(description="Create quick plots from data files")
parser.add_argument("data_file", help="CSV or JSON data file")
parser.add_argument(
"--type",
"-t",
choices=["line", "bar", "scatter"],
default="bar",
help="Plot type (default: bar)",
)
parser.add_argument("--x", default=None, help="X-axis column name")
parser.add_argument("--y", default=None, help="Y-axis column name")
parser.add_argument(
"--list-columns", "-l", action="store_true", help="List available columns"
)
args = parser.parse_args()
try:
headers, data = load_data(args.data_file)
except Exception as e:
print(f"β Error loading data: {e}")
return 1
if args.list_columns or not headers:
print(f"π Available columns in {args.data_file}:")
for h in headers:
sample = data[0].get(h, "") if data else ""
print(f" - {h}: {str(sample)[:30]}...")
return 0
# Auto-select columns if not specified
x_col = args.x or headers[0]
y_col = args.y or (headers[1] if len(headers) > 1 else headers[0])
if x_col not in headers:
print(f"β Column not found: {x_col}")
print(f" Available: {', '.join(headers)}")
return 1
if y_col not in headers:
print(f"β Column not found: {y_col}")
print(f" Available: {', '.join(headers)}")
return 1
plot = create_text_plot(data, x_col, y_col, args.type)
print(plot)
return 0
if __name__ == "__main__":
sys.exit(main())