简体   繁体   中英

Python: Altair: Conditionally change axis label appearance (color, opacity)

Currently, Vega does not support interactive axis labels, ie creating a selection via clicking on labels of an axis (see issue 1657 ), and so neither does Altair.

Therefore I am trying to find a work-around by providing legend selection and changing the appearance of the axis labels.

I am able to color labels conditionally (see code example below).

import altair as alt
from vega_datasets import data
source = data.unemployment_across_industries.url

selection = alt.selection_multi(fields=['series'], bind='legend')

alt.Chart(source).mark_bar().encode(
alt.X('series:N', axis=alt.Axis(labelColor=alt.condition('datum.value == "Finance"', alt.value('red'), alt.value('black')))),
alt.Y('sum(count):Q'),
alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
).add_selection(
    selection
)

However, I get an error when trying to use a selection instead of an expression.

alt.X('series:N', axis=alt.Axis(labelColor=alt.condition(selection, alt.value('red'), alt.value('black')))),

Is there any way of connecting the label appearance to a selection (here: bound to the legend)?

Did not find a way to dynamically change the axis labels, but managed to get close to a solution by displaying the axis labels via mark_text

bars = alt.Chart(source).mark_bar().encode(
    alt.X('series:N', axis=alt.Axis(labels=False, title="")),
    alt.Y('sum(count):Q'),
    alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
    opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
).add_selection(
    selection
)

labels = alt.Chart(source).mark_text(align='right', angle=270).encode(
    alt.X('series:N', axis=None),
    text='series:N',
    opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
).transform_aggregate(
    groupby=["series"]
)

(bars & labels).configure(
    concat=alt.CompositionConfig(spacing=0)
).configure_view(
    strokeWidth=0
)

显示选择标签的简短动画,不仅反映在条形图中,还反映在轴标签中

(Would still love to learn about better solutions.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM