|
|
import json |
|
|
from pathlib import Path |
|
|
|
|
|
|
|
|
class PlotRegistry: |
|
|
def __init__(self, json_path: str): |
|
|
self.path = Path(json_path) |
|
|
with open(self.path, "r", encoding="utf-8") as f: |
|
|
self.registry = json.load(f) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_groups(self): |
|
|
return list(self.registry.keys()) |
|
|
|
|
|
def get_plots_in_group(self, group: str): |
|
|
return self.registry[group] |
|
|
|
|
|
def get_plot(self, group: str, plot_key: str): |
|
|
return self.registry[group][plot_key] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate_code( |
|
|
self, |
|
|
group: str, |
|
|
plot_key: str, |
|
|
variables: dict, |
|
|
user_options: dict, |
|
|
figsize=(8, 5), |
|
|
title: str = "", |
|
|
xlabel: str = "", |
|
|
ylabel: str = "", |
|
|
): |
|
|
plot = self.get_plot(group, plot_key) |
|
|
|
|
|
|
|
|
base_func = plot["code_template"].split("(")[0] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
exec_args = ["data=df", "ax=ax"] |
|
|
display_args = ["data=df"] |
|
|
|
|
|
|
|
|
for name, value in variables.items(): |
|
|
if value is not None: |
|
|
exec_args.append(f"{name}={name}") |
|
|
display_args.append(f"{name}='{value}'") |
|
|
|
|
|
|
|
|
for k, v in user_options.items(): |
|
|
if v not in ("", None): |
|
|
exec_args.append(f"{k}={k}") |
|
|
if isinstance(v, str): |
|
|
display_args.append(f"{k}={repr(v)}") |
|
|
else: |
|
|
display_args.append(f"{k}={v}") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
exec_plot_line = f"{base_func}({', '.join(exec_args)})" |
|
|
display_plot_line = f"{base_func}({', '.join(display_args)})" |
|
|
|
|
|
exec_code = f""" |
|
|
# --- plotting --- |
|
|
{exec_plot_line} |
|
|
ax.set_title({repr(title)}) |
|
|
ax.set_xlabel({repr(xlabel)}) |
|
|
ax.set_ylabel({repr(ylabel)}) |
|
|
""" |
|
|
display_code = f""" |
|
|
import matplotlib.pyplot as plt |
|
|
import seaborn as sns |
|
|
|
|
|
fig, ax = plt.subplots(figsize={figsize}) |
|
|
{display_plot_line} |
|
|
ax.set_title({repr(title)}) |
|
|
ax.set_xlabel({repr(xlabel)}) |
|
|
ax.set_ylabel({repr(ylabel)}) |
|
|
plt.show() |
|
|
""".strip() |
|
|
|
|
|
return exec_code.strip(), display_code |