saving plots to subdirectories grouped by filter
This commit is contained in:
56
plots.py
56
plots.py
@@ -24,10 +24,66 @@ class JPMCPlotsMixin:
|
||||
# Lowercase and limit length
|
||||
return clean.lower()[:100]
|
||||
|
||||
def _get_filter_slug(self) -> str:
|
||||
"""Generate a directory-friendly slug based on active filters."""
|
||||
parts = []
|
||||
|
||||
# Mapping of attribute name to (short_code, value, options_attr)
|
||||
filters = [
|
||||
('age', 'Age', getattr(self, 'filter_age', None), 'options_age'),
|
||||
('gender', 'Gen', getattr(self, 'filter_gender', None), 'options_gender'),
|
||||
('consumer', 'Cons', getattr(self, 'filter_consumer', None), 'options_consumer'),
|
||||
('ethnicity', 'Eth', getattr(self, 'filter_ethnicity', None), 'options_ethnicity'),
|
||||
('income', 'Inc', getattr(self, 'filter_income', None), 'options_income'),
|
||||
]
|
||||
|
||||
for _, short_code, value, options_attr in filters:
|
||||
if value is None:
|
||||
continue
|
||||
|
||||
# Ensure value is a list for uniform handling
|
||||
if not isinstance(value, list):
|
||||
value = [value]
|
||||
|
||||
if len(value) == 0:
|
||||
continue
|
||||
|
||||
# Check if all options are selected (equivalent to no filter)
|
||||
# We compare the set of selected values to the set of all available options
|
||||
master_list = getattr(self, options_attr, None)
|
||||
if master_list and set(value) == set(master_list):
|
||||
continue
|
||||
|
||||
if len(value) > 3:
|
||||
# If more than 3 options selected, use count to keep slug short
|
||||
val_str = f"{len(value)}_grps"
|
||||
else:
|
||||
# Join values with '+'
|
||||
clean_values = []
|
||||
for v in value:
|
||||
# Simple sanitization: keep alphanum and hyphens/dots, remove others
|
||||
s = str(v)
|
||||
# Remove special chars that might be problematic in dir names
|
||||
s = re.sub(r'[^\w\-\.]', '', s)
|
||||
clean_values.append(s)
|
||||
val_str = "+".join(clean_values)
|
||||
|
||||
parts.append(f"{short_code}-{val_str}")
|
||||
|
||||
if not parts:
|
||||
return "All_Respondents"
|
||||
|
||||
return "_".join(parts)
|
||||
|
||||
def _save_plot(self, fig: go.Figure, title: str) -> None:
|
||||
"""Save plot to PNG file if fig_save_dir is set."""
|
||||
if hasattr(self, 'fig_save_dir') and self.fig_save_dir:
|
||||
path = Path(self.fig_save_dir)
|
||||
|
||||
# Add filter slug subfolder
|
||||
filter_slug = self._get_filter_slug()
|
||||
path = path / filter_slug
|
||||
|
||||
if not path.exists():
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user