Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Promote when-then-otherwise in User Guide #3544

Open
wants to merge 42 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
e46a493
docs: Replace some inline references
dangotbanned Aug 18, 2024
abdcf3a
Merge branch 'main' into when-then-user-guide
dangotbanned Aug 27, 2024
a365083
Merge remote-tracking branch 'upstream/main' into when-then-user-guide
dangotbanned Aug 28, 2024
9ca55a8
Merge branch 'when-then-user-guide' of https://github.com/dangotbanne…
dangotbanned Aug 28, 2024
a681ec5
docs: Update `waterfall_chart.py` example
dangotbanned Aug 28, 2024
f454093
wip
dangotbanned Aug 28, 2024
ab6c4b4
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 1, 2024
3b72a83
Merge branch 'when-then-user-guide' of https://github.com/dangotbanne…
dangotbanned Sep 2, 2024
089759e
Merge remote-tracking branch 'upstream/main' into when-then-user-guide
dangotbanned Sep 4, 2024
729b7de
docs: Use `when` in `expressions.rst`
dangotbanned Sep 4, 2024
1bc65ce
docs: Use `when` in `bindings_widgets.rst`
dangotbanned Sep 4, 2024
f9277fa
docs: Use `when` in `exploring-weather.rst`
dangotbanned Sep 4, 2024
961eb13
docs: Use `when` in `filter.rst`
dangotbanned Sep 4, 2024
d886fbe
docs: Use `when` in `pivot.rst`
dangotbanned Sep 4, 2024
9ca591e
docs: Use `when` in `compound_charts.rst`
dangotbanned Sep 4, 2024
fe5f8e5
docs: Use `when` in `times_and_dates.rst`
dangotbanned Sep 4, 2024
b0893e2
docs: Use `when` in `line.rst`
dangotbanned Sep 4, 2024
008ff8d
docs: Use `when` in `text.rst`
dangotbanned Sep 4, 2024
4fe1e9c
docs: Use `when` in `geoshape.rst`
dangotbanned Sep 4, 2024
6269533
docs: Use `when` in `README.md`
dangotbanned Sep 4, 2024
f08d96f
docs: Use `when` in `jupyter_chart.rst`
dangotbanned Sep 4, 2024
60f859f
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 5, 2024
1d6be16
docs(DRAFT): Use `when` in `parameters.rst`
dangotbanned Sep 5, 2024
d9899f5
docs: Proofread `parameters.rst`
dangotbanned Sep 5, 2024
e6a9b9c
docs: Add callout referencing change
dangotbanned Sep 5, 2024
dfab00c
docs: Use `when` in all methods syntax examples
dangotbanned Sep 5, 2024
ff0bc34
docs: Use `when` in arguments syntax examples (1/2)
dangotbanned Sep 6, 2024
390d599
docs: Use `when` in arguments syntax examples (2/2)
dangotbanned Sep 6, 2024
e6790a9
Merge remote-tracking branch 'upstream/main' into when-then-user-guide
dangotbanned Sep 6, 2024
3caf2e7
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 6, 2024
ebff622
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 6, 2024
731728e
Merge branch 'when-then-user-guide' of https://github.com/dangotbanne…
dangotbanned Sep 6, 2024
1a5c0b9
Merge remote-tracking branch 'upstream/main' into when-then-user-guide
dangotbanned Sep 6, 2024
6d6b8a6
chore(typing): Removed fixed ignore comments
dangotbanned Sep 6, 2024
222deb5
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 9, 2024
1c7663c
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 10, 2024
9ebb90b
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 12, 2024
f43d331
Merge branch 'main' into when-then-user-guide
dangotbanned Sep 17, 2024
fb42da7
fix: Use `selector` argument in `make_example`
dangotbanned Sep 18, 2024
50a520e
docs: Add new subsection content
dangotbanned Sep 18, 2024
df5555c
docs: Add link to `interactive_bar_select_highlight.rst`
dangotbanned Sep 18, 2024
e363abd
Expand explanation of `when`
joelostblom Sep 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ brush = alt.selection_interval()
points = alt.Chart(source).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon',
color=alt.condition(brush, 'Origin', alt.value('lightgray'))
color=alt.when(brush).then("Origin").otherwise(alt.value("lightgray"))
).add_params(
brush
)
Expand Down
31 changes: 21 additions & 10 deletions altair/vegalite/v5/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -859,14 +859,17 @@ def then(self, statement: _StatementType, /, **kwds: Any) -> Then[Any]:
A spec or value to use when the preceding :func:`.when()` clause is true.

.. note::
``str`` will be encoded as `shorthand<https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands>`__.
``str`` will be encoded as `shorthand`_.
**kwds
Additional keyword args are added to the resulting ``dict``.

Returns
-------
:class:`Then`

.. _shorthand:
https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands

Examples
--------
Simple conditions may be expressed without defining a default::
Expand Down Expand Up @@ -939,10 +942,12 @@ def otherwise(
Roughly equivalent to an ``else`` clause.

.. note::
``str`` will be encoded as `shorthand<https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands>`__.
``str`` will be encoded as `shorthand`_.
**kwds
Additional keyword args are added to the resulting ``dict``.

.. _shorthand:
https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands

Examples
--------
Expand Down Expand Up @@ -1020,14 +1025,16 @@ def when(
When ``predicate`` is a ``Parameter`` that is used more than once,
``alt.when().then().when(..., empty=...)`` provides granular control for each occurrence.
**constraints
Specify `Field Equal Predicate <https://vega.github.io/vega-lite/docs/predicate.html#equal-predicate>`__'s.
Specify `Field Equal Predicate`_'s.
Shortcut for ``alt.datum.field_name == value``, see examples for usage.

Returns
-------
:class:`ChainedWhen`
A partial state which requires calling :meth:`ChainedWhen.then()` to finish the condition.

.. _Field Equal Predicate:
https://vega.github.io/vega-lite/docs/predicate.html#equal-predicate

Examples
--------
Expand Down Expand Up @@ -1115,14 +1122,17 @@ def then(self, statement: _StatementType, /, **kwds: Any) -> Then[_Conditions]:
A spec or value to use when the preceding :meth:`Then.when()` clause is true.

.. note::
``str`` will be encoded as `shorthand<https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands>`__.
``str`` will be encoded as `shorthand`_.
**kwds
Additional keyword args are added to the resulting ``dict``.

Returns
-------
:class:`Then`

.. _shorthand:
https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands

Examples
--------
Multiple conditions with an implicit default::
Expand Down Expand Up @@ -1177,7 +1187,7 @@ def when(
When ``predicate`` is a ``Parameter`` that is used more than once,
``alt.when(..., empty=...)`` provides granular control for each occurrence.
**constraints
Specify `Field Equal Predicate <https://vega.github.io/vega-lite/docs/predicate.html#equal-predicate>`__'s.
Specify `Field Equal Predicate`_'s.
Shortcut for ``alt.datum.field_name == value``, see examples for usage.

Returns
Expand All @@ -1187,11 +1197,12 @@ def when(

Notes
-----
- Directly inspired by the ``when-then-otherwise`` syntax used in ``polars.when``.
- Directly inspired by the ``when-then-otherwise`` syntax used in `polars.when`_.

References
----------
`polars.when <https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html>`__
.. _Field Equal Predicate:
https://vega.github.io/vega-lite/docs/predicate.html#equal-predicate
.. _polars.when:
https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html

Examples
--------
Expand Down Expand Up @@ -4907,7 +4918,7 @@ def remove_prop(subchart: ChartType, prop: str) -> ChartType:
# or it must be Undefined or identical to proceed.
output_dict[prop] = chart[prop]
else:
msg = f"There are inconsistent values {values} for {prop}"
msg = f"There are inconsistent values {values} for {prop}" # pyright: ignore[reportPossiblyUnboundVariable]
raise ValueError(msg)
subcharts = [remove_prop(c, prop) for c in subcharts]

Expand Down
48 changes: 24 additions & 24 deletions doc/case_studies/exploring-weather.rst
Original file line number Diff line number Diff line change
Expand Up @@ -226,33 +226,33 @@ of the selection (for more information on selections, see
.. altair-plot::

brush = alt.selection_interval()

points = alt.Chart().mark_point().encode(
alt.X('temp_max:Q').title('Maximum Daily Temperature (C)'),
alt.Y('temp_range:Q').title('Daily Temperature Range (C)'),
color=alt.condition(brush, 'weather:N', alt.value('lightgray'), scale=scale),
size=alt.Size('precipitation:Q').scale(range=[1, 200])
).transform_calculate(
"temp_range", "datum.temp_max - datum.temp_min"
).properties(
width=600,
height=400
).add_params(
brush
color = (
alt.when(brush)
.then(alt.Color("weather:N").scale(scale))
.otherwise(alt.value("lightgray"))
)

bars = alt.Chart().mark_bar().encode(
x='count()',
y='weather:N',
color=alt.Color('weather:N').scale(scale),
).transform_calculate(
"temp_range", "datum.temp_max - datum.temp_min"
).transform_filter(
brush
).properties(
width=600
points = (
alt.Chart()
.mark_point()
.encode(
alt.X("temp_max:Q").title("Maximum Daily Temperature (C)"),
alt.Y("temp_range:Q").title("Daily Temperature Range (C)"),
color=color,
size=alt.Size("precipitation:Q").scale(range=[1, 200]),
)
.transform_calculate("temp_range", "datum.temp_max - datum.temp_min")
.properties(width=600, height=400)
.add_params(brush)
)
bars = (
alt.Chart()
.mark_bar()
.encode(x="count()", y="weather:N", color=alt.Color("weather:N").scale(scale))
.transform_calculate("temp_range", "datum.temp_max - datum.temp_min")
.transform_filter(brush)
.properties(width=600)
dangotbanned marked this conversation as resolved.
Show resolved Hide resolved
)

alt.vconcat(points, bars, data=df)

This chart, containing concatenations, data transformations, selections, and
Expand Down
34 changes: 15 additions & 19 deletions doc/user_guide/compound_charts.rst
Original file line number Diff line number Diff line change
Expand Up @@ -364,28 +364,24 @@ layered chart with a hover selection:
.. altair-plot::

hover = alt.selection_point(on='pointerover', nearest=True, empty=False)

base = alt.Chart(iris).encode(
x='petalLength:Q',
y='petalWidth:Q',
color=alt.condition(hover, 'species:N', alt.value('lightgray'))
).properties(
width=180,
height=180,
when_hover = alt.when(hover)

base = (
alt.Chart(iris)
.encode(
x="petalLength:Q",
y="petalWidth:Q",
color=when_hover.then("species:N").otherwise(alt.value("lightgray")),
)
.properties(width=180, height=180)
)

points = base.mark_point().add_params(
hover
)

points = base.mark_point().add_params(hover)
text = base.mark_text(dy=-5).encode(
text = 'species:N',
opacity = alt.condition(hover, alt.value(1), alt.value(0))
)

alt.layer(points, text).facet(
'species:N',
text="species:N",
opacity=when_hover.then(alt.value(1)).otherwise(alt.value(0)),
)

(points + text).facet("species:N")

Though each of the above examples have faceted the data across columns,
faceting across rows (or across rows *and* columns) is supported as
Expand Down
40 changes: 12 additions & 28 deletions doc/user_guide/interactions/bindings_widgets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ where a drop-down is used to highlight cars of a specific ``Origin``:

input_dropdown = alt.binding_select(options=['Europe', 'Japan', 'USA'], name='Region ')
selection = alt.selection_point(fields=['Origin'], bind=input_dropdown)
color = alt.condition(
selection,
alt.Color('Origin:N').legend(None),
alt.value('lightgray')
color = (
alt.when(selection)
.then(alt.Color("Origin:N").legend(None))
.otherwise(alt.value("lightgray"))
)

alt.Chart(cars).mark_point().encode(
Expand All @@ -72,7 +72,7 @@ and selection parameters follow the same pattern as you will see further down
in the :ref:`encoding-channel-binding` section.

As you can see above,
we are still using ``conditions`` to make the chart respond to the selection,
we are still using :ref:`conditions <conditions>` to make the chart respond to the selection,
just as we did without widgets.
Bindings and input elements can also be used to filter data
allowing the user to see just the selected points as in the example below.
Expand Down Expand Up @@ -137,11 +137,7 @@ to see the point highlighted
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
tooltip='Name:N',
opacity=alt.condition(
search_input,
alt.value(1),
alt.value(0.05)
)
opacity=alt.when(search_input).then(alt.value(1)).otherwise(alt.value(0.05)),
).add_params(
search_input
)
Expand Down Expand Up @@ -185,16 +181,12 @@ which would have been the case if we just wrote ``xval < selector``.

slider = alt.binding_range(min=0, max=100, step=1, name='Cutoff ')
selector = alt.param(name='SelectorName', value=50, bind=slider)
predicate = alt.datum.xval < selector

alt.Chart(df).mark_point().encode(
x='xval',
y='yval',
color=alt.condition(
alt.datum.xval < selector,
# 'datum.xval < SelectorName', # An equivalent alternative
alt.value('red'),
alt.value('blue')
)
color=alt.when(predicate).then(alt.value("red")).otherwise(alt.value("blue")),
).add_params(
selector
)
Expand All @@ -213,16 +205,12 @@ points based on whether they are smaller or larger than the value:
bind=slider,
value=[{'cutoff': 50}]
)
predicate = alt.datum.xval < selector.cutoff

alt.Chart(df).mark_point().encode(
x='xval',
y='yval',
color=alt.condition(
alt.datum.xval < selector.cutoff,
# 'datum.xval < SelectorName.cutoff', # An equivalent alternative
alt.value('red'),
alt.value('blue')
)
color=alt.when(predicate).then(alt.value("red")).otherwise(alt.value("blue")),
).add_params(
selector
)
Expand Down Expand Up @@ -263,11 +251,7 @@ just if the value of the check box is True (checked) or False (unchecked):
alt.Chart(cars).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
size=alt.condition(
param_checkbox,
'Acceleration:Q',
alt.value(25)
)
size=alt.when(param_checkbox).then("Acceleration:Q").otherwise(alt.value(25)),
).add_params(
param_checkbox
)
Expand Down Expand Up @@ -315,7 +299,7 @@ Altair provides the ``bind='legend'`` option to facilitate the creation of click
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color='Origin:N',
opacity=alt.condition(selection, alt.value(0.8), alt.value(0.2))
opacity=alt.when(selection).then(alt.value(0.8)).otherwise(alt.value(0.2)),
).add_params(
selection
)
Expand Down
13 changes: 4 additions & 9 deletions doc/user_guide/interactions/expressions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -169,19 +169,14 @@ To try this out, you can type ``mazda|ford`` in the search input box below.
name='Search ',
)
)
search_matches = alt.expr.test(alt.expr.regexp(search_input, "i"), alt.datum.Name)

alt.Chart(cars).mark_point(size=60).encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
tooltip='Name:N',
opacity=alt.condition(
alt.expr.test(alt.expr.regexp(search_input, 'i'), alt.datum.Name),
# f"test(regexp({search_input.name}, 'i'), datum.Name)", # Equivalent js alternative
alt.value(1),
alt.value(0.05)
)
).add_params(
search_input
)
opacity=alt.when(search_matches).then(alt.value(1)).otherwise(alt.value(0.05)),
).add_params(search_input)

And remember, all this interactivity is client side.
You can save this chart as an HTML file or put it on a static site generator such as GitHub/GitLab pages
Expand Down
Loading