Skip to content

Commit

Permalink
Replacing chart/-s with figure/-s where necessary.
Browse files Browse the repository at this point in the history
  • Loading branch information
petar-qb committed Oct 27, 2023
1 parent bd21f02 commit 0383f02
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 42 deletions.
16 changes: 8 additions & 8 deletions vizro-core/src/vizro/actions/_actions_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,23 @@ def _apply_filters(
return data_frame


def _apply_chart_filter_interaction(
def _apply_graph_filter_interaction(
data_frame: pd.DataFrame, target: str, ctd_filter_interaction: Dict[str, CallbackTriggerDict]
) -> pd.DataFrame:
ctd_click_data = ctd_filter_interaction["clickData"]
if not ctd_click_data["value"]:
return data_frame

source_chart_id: ModelID = ctd_click_data["id"]
source_chart_actions = _get_component_actions(model_manager[source_chart_id])
source_graph_id: ModelID = ctd_click_data["id"]
source_graph_actions = _get_component_actions(model_manager[source_graph_id])
try:
custom_data_columns = model_manager[source_chart_id]["custom_data"] # type: ignore[index]
custom_data_columns = model_manager[source_graph_id]["custom_data"] # type: ignore[index]
except KeyError as exc:
raise KeyError(f"No `custom_data` argument found for source chart with id {source_chart_id}.") from exc
raise KeyError(f"No `custom_data` argument found for source graph with id {source_graph_id}.") from exc

customdata = ctd_click_data["value"]["points"][0]["customdata"]

for action in source_chart_actions:
for action in source_graph_actions:
if target not in action.function["targets"]:
continue
for custom_data_idx, column in enumerate(custom_data_columns):
Expand Down Expand Up @@ -130,7 +130,7 @@ def _apply_filter_interaction(
) -> pd.DataFrame:
for ctd_filter_interaction in ctds_filter_interaction:
if "clickData" in ctd_filter_interaction:
data_frame = _apply_chart_filter_interaction(
data_frame = _apply_graph_filter_interaction(
data_frame=data_frame,
target=target,
ctd_filter_interaction=ctd_filter_interaction,
Expand Down Expand Up @@ -236,7 +236,7 @@ def _get_filtered_data(
return filtered_data


def _get_modified_page_charts(
def _get_modified_page_figures(
ctds_filter: List[CallbackTriggerDict],
ctds_filter_interaction: List[Dict[str, CallbackTriggerDict]],
ctds_parameters: List[CallbackTriggerDict],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,16 @@ def _get_inputs_of_controls(action_id: ModelID, control_type: ControlType) -> Li
]


def _get_inputs_of_chart_interactions(
def _get_inputs_of_figure_interactions(
action_id: ModelID, action_function: Callable[[Any], Dict[str, Any]]
) -> List[Dict[str, State]]:
"""Gets list of States for selected chart interaction `action_name` of triggered page."""
chart_interactions_on_page = _get_matching_actions_by_function(
"""Gets list of States for selected figure interaction `action_name` of triggered page."""
figure_interactions_on_page = _get_matching_actions_by_function(
page=_get_triggered_page(action_id=action_id),
action_function=action_function,
)
inputs = []
for action in chart_interactions_on_page:
for action in figure_interactions_on_page:
triggered_model = _get_triggered_model(action_id=ModelID(str(action.id)))
if isinstance(triggered_model, Table):
inputs.append(
Expand Down Expand Up @@ -149,7 +149,7 @@ def _get_action_callback_inputs(action_id: ModelID) -> Dict[str, Any]:
),
# TODO: Probably need to adjust other inputs to follow the same structure List[Dict[str, State]]
"filter_interaction": (
_get_inputs_of_chart_interactions(action_id=action_id, action_function=filter_interaction.__wrapped__)
_get_inputs_of_figure_interactions(action_id=action_id, action_function=filter_interaction.__wrapped__)
if "filter_interaction" in include_inputs
else []
),
Expand Down
8 changes: 4 additions & 4 deletions vizro-core/src/vizro/actions/_filter_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from dash import ctx

from vizro.actions._actions_utils import (
_get_modified_page_charts,
_get_modified_page_figures,
)
from vizro.managers._model_manager import ModelID
from vizro.models.types import capture
Expand All @@ -19,7 +19,7 @@ def _filter(
filter_function: Callable[[pd.Series, Any], pd.Series],
**inputs: Dict[str, Any],
) -> Dict[ModelID, Any]:
"""Filters targeted charts/components on page by interaction with `Filter` control.
"""Filters targeted figures/components on page by interaction with `Filter` control.
Args:
filter_column: Data column to filter
Expand All @@ -29,9 +29,9 @@ def _filter(
inputs = {'filters': [], 'parameters': ['gdpPercap'], 'filter_interaction': [], 'theme_selector': True}
Returns:
Dict mapping target component ids to modified charts/components e.g. {'my_scatter': Figure({})}
Dict mapping target component ids to modified figures/components e.g. {'my_scatter': Figure({})}
"""
return _get_modified_page_charts(
return _get_modified_page_figures(
targets=targets,
ctds_filter=ctx.args_grouping["filters"],
ctds_filter_interaction=ctx.args_grouping["filter_interaction"],
Expand Down
8 changes: 4 additions & 4 deletions vizro-core/src/vizro/actions/_on_page_load_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from dash import ctx

from vizro.actions._actions_utils import (
_get_modified_page_charts,
_get_modified_page_figures,
)
from vizro.managers import data_manager, model_manager
from vizro.managers._model_manager import ModelID
Expand All @@ -14,19 +14,19 @@

@capture("action")
def _on_page_load(page_id: ModelID, **inputs: Dict[str, Any]) -> Dict[ModelID, Any]:
"""Applies controls to charts on page once the page is opened (or refreshed).
"""Applies controls to figures on page once the page is opened (or refreshed).
Args:
page_id: Page ID of relevant page
inputs: Dict mapping action function names with their inputs e.g.
inputs = {'filters': [], 'parameters': ['gdpPercap'], 'filter_interaction': [], 'theme_selector': True}
Returns:
Dict mapping targeted chart ids to modified figures e.g. {'my_scatter': Figure({})}
Dict mapping target component ids to modified figures e.g. {'my_scatter': Figure({})}
"""
targets = [component.id for component in model_manager[page_id].components if data_manager._has_registered_data(component.id)] # type: ignore[attr-defined] # noqa: E501

return _get_modified_page_charts(
return _get_modified_page_figures(
targets=targets,
ctds_filter=ctx.args_grouping["filters"],
ctds_filter_interaction=ctx.args_grouping["filter_interaction"],
Expand Down
9 changes: 4 additions & 5 deletions vizro-core/src/vizro/actions/_parameter_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,27 @@
from dash import ctx

from vizro.actions._actions_utils import (
_get_modified_page_charts,
_get_modified_page_figures,
)
from vizro.managers._model_manager import ModelID
from vizro.models.types import capture


# TODO - consider using dash.Patch() for parameter action
@capture("action")
def _parameter(targets: List[str], **inputs: Dict[str, Any]) -> Dict[ModelID, Any]:
"""Modifies parameters of targeted charts/components on page.
"""Modifies parameters of targeted figures/components on page.
Args:
targets: List of target component ids to change parameters of.
inputs: Dict mapping action function names with their inputs e.g.
inputs = {'filters': [], 'parameters': ['gdpPercap'], 'filter_interaction': [], 'theme_selector': True}
Returns:
Dict mapping target component ids to modified charts/components e.g. {'my_scatter': Figure({})}
Dict mapping target component ids to modified figures/components e.g. {'my_scatter': Figure({})}
"""
target_ids: List[ModelID] = [target.split(".")[0] for target in targets] # type: ignore[misc]

return _get_modified_page_charts(
return _get_modified_page_figures(
targets=target_ids,
ctds_filter=ctx.args_grouping["filters"],
ctds_filter_interaction=ctx.args_grouping["filter_interaction"],
Expand Down
4 changes: 2 additions & 2 deletions vizro-core/src/vizro/actions/export_data_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def export_data(
file_format: Literal["csv", "xlsx"] = "csv",
**inputs: Dict[str, Any],
) -> Dict[str, Any]:
"""Exports visible data of target charts/components on page after being triggered.
"""Exports visible data of target figures/components on page after being triggered.
Args:
targets: List of target component ids to download data from. Defaults to None.
Expand All @@ -32,7 +32,7 @@ def export_data(
ValueError: If target component does not exist on page.
Returns:
Dict mapping target component id to modified charts/components e.g. {'my_scatter': Figure({})}
Dict mapping target component id to modified figures/components e.g. {'my_scatter': Figure({})}
"""
if not targets:
targets = [
Expand Down
16 changes: 9 additions & 7 deletions vizro-core/src/vizro/actions/filter_interaction_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from dash import ctx

from vizro.actions._actions_utils import (
_get_modified_page_charts,
_get_modified_page_figures,
)
from vizro.managers._model_manager import ModelID
from vizro.models.types import capture
Expand All @@ -16,21 +16,23 @@ def filter_interaction(
targets: Optional[List[ModelID]] = None,
**inputs: Dict[str, Any],
) -> Dict[ModelID, Any]:
"""Filters targeted charts/components on page by clicking on data points of the source chart.
"""Filters targeted figures/components on page by clicking on data points or table cells of the source figure.
To set up filtering on specific columns of the target chart(s), include these columns in the 'custom_data'
parameter of the source chart e.g. `px.bar(..., custom_data=["species", "sepal_length"])`
To set up filtering on specific columns of the target graph(s), include these columns in the 'custom_data'
parameter of the source graph e.g. `px.bar(..., custom_data=["species", "sepal_length"])`.
If filter interaction source is table e.g. `vm.Table(..., actions=[filter_interaction])`, then the table doesn't
need to have 'custom_data' parameter set up.
Args:
targets: List of target component ids to filter by chart interaction. If missing, will target all valid
targets: List of target component ids to filter by figure interaction. If missing, will target all valid
components on page. Defaults to None.
inputs: Dict mapping action function names with their inputs e.g.
inputs = {'filters': [], 'parameters': ['gdpPercap'], 'filter_interaction': [], 'theme_selector': True}
Returns:
Dict mapping target component ids to modified charts/components e.g. {'my_scatter': Figure({})}
Dict mapping target component ids to modified figures/components e.g. {'my_scatter': Figure({})}
"""
return _get_modified_page_charts(
return _get_modified_page_figures(
targets=targets,
ctds_filter=ctx.args_grouping["filters"],
ctds_filter_interaction=ctx.args_grouping["filter_interaction"],
Expand Down
4 changes: 2 additions & 2 deletions vizro-core/src/vizro/models/_controls/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ def _set_slider_values(self):
max_values.append(data_frame[self.column].max())
if not is_numeric_dtype(pd.Series(min_values)) or not is_numeric_dtype(pd.Series(max_values)):
raise ValueError(
f"Non-numeric values detected in the shared data column '{self.column}' for targeted charts. "
f"Please ensure that the data column contains the same data type across all targeted charts."
f"Non-numeric values detected in the shared data column '{self.column}' for targeted figures. "
f"Please ensure that the data column contains the same data type across all targeted figures."
)
if self.selector.min is None:
self.selector.min = min(min_values)
Expand Down
2 changes: 1 addition & 1 deletion vizro-core/src/vizro/models/_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def _get_grid_lines(grid: List[List[int]]) -> Tuple[List[ColRowGridLines], List[


class Layout(VizroBaseModel):
"""Grid specification to place chart/components on the [`Page`][vizro.models.Page].
"""Grid specification to place figures/components on the [`Page`][vizro.models.Page].
Args:
grid (List[List[int]]): Grid specification to arrange components on screen.
Expand Down
2 changes: 1 addition & 1 deletion vizro-core/src/vizro/plotly/express.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from vizro.models.types import capture


# TODO: is there a better way to see if the import is a chart? Don't want to check return type though. -> MS
# TODO: is there a better way to see if the import is a graph? Don't want to check return type though. -> MS
# Might also want to define __dir__ or __all__ in order to facilitate IDE completion etc.
# TODO: type hints -> MS
def __getattr__(name: str) -> Any:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def test_filter_interaction_without_targets_temporary_behavior( # temporary fix

assert result == {}

@pytest.mark.xfail # This is the desired behavior, ie when no target is provided, then all charts filtered
@pytest.mark.xfail # This is the desired behavior, ie when no target is provided, then all figures filtered
@pytest.mark.parametrize(
"callback_context_filter_interaction," "target_scatter_filtered_continent," "target_box_filtered_continent",
[
Expand Down
4 changes: 2 additions & 2 deletions vizro-core/tests/unit/vizro/models/_controls/test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ def test_set_slider_values_shared_column_inconsistent_dtype(
model_manager["graphs_with_shared_column"].controls = [filter]
with pytest.raises(
ValueError,
match=f"Non-numeric values detected in the shared data column '{filter.column}' for targeted charts. "
f"Please ensure that the data column contains the same data type across all targeted charts.",
match=f"Non-numeric values detected in the shared data column '{filter.column}' for targeted figures. "
f"Please ensure that the data column contains the same data type across all targeted figures.",
):
filter.pre_build()

Expand Down

0 comments on commit 0383f02

Please sign in to comment.