Search code examples
altairvega-litevega

Vega-Lite/Altair adding labels to select dropdown


I'm trying to find a way to add labels to a binding_select in altair/vega-lite. At the moment it seems like the only way to customise the values shown in a select ui element is to change the names of the columns. This works for the regular values, but how can the label of the "None" value be changed that clears the selection? Im trying to do this in order to be able to make charts publicly available. With a "null" value in the select ui, it might be confusing.

region_dropdown = alt.binding_select(
    options = [None, 'CHN', 'IND', 'RUS', 'USA', 'AFR', 'LAM', 'EUR']
)

region_selection = alt.selection_single(
    fields=['region'], 
    bind=region_dropdown, 
    init={'region': 'USA'}
)

alt.Chart(data).transform_calculate(
  per_capita='datum.cum_co2/datum.cum_population'
).encode(
  x='year',
  y=alt.Y('mean(per_capita):Q'),
  color=alt.condition(region_selection, 'region:N', alt.value('rgba(0,0,0,0.05)')), 
  detail='region:N'
).mark_line().add_selection(region_selection)

Solution

  • You can use the labels option in binding_select to rename your selection labels:

    region_dropdown = alt.binding_select(
        options = [None, 'CHN', 'IND', 'RUS', 'USA', 'AFR', 'LAM', 'EUR'],
        labels = ['All', 'CHN', 'IND', 'RUS', 'USA', 'AFR', 'LAM', 'EUR']
    )
    

    Example:

    import altair as alt
    import vega_datasets
    
    data = vega_datasets.data.cars()
    
    region_dropdown = alt.binding_select(
        options = [None, 'USA', 'Europe', 'Japan'],
        labels = ['All', 'USA', 'Europe', 'Japan']
    )
    
    region_selection = alt.selection_single(
        fields=['Origin'], 
        bind=region_dropdown, 
        init={'Origin': 'USA'}
    )
    
    alt.Chart(data).encode(
      x='Year',
      y=alt.Y('mean(Horsepower):Q'),
      color=alt.condition(region_selection, 'Origin:N', alt.value('rgba(0,0,0,0.05)')), 
      detail='Origin:N'
    ).mark_line().add_selection(region_selection)
    

    enter image description here