Search code examples
pythonaltair

How to change attribute based on boolean condition


I am trying to alter point size based on whether its name exists in a list or not, I've tried many different ways but I keep generating this error.

Code:


    graph = alt.Chart(df).mark_point( filled = False).encode(
        x=alt.X(axe_x),
        y=alt.Y(axe_y),
        size=alt.condition(
            (alt.datum.name) in (some_list),
            alt.value(150),
            alt.value(50))

    )

Error: NotImplementedError: condition predicate of type <class 'bool'>

How can I get around this?


Solution

  • You can use a transform_lookup for this

    import altair as alt
    import pandas as pd
    from vega_datasets import data
    source = data.cars()
    # lookup table matching the string to corresonding size
    df2 = pd.DataFrame({
        'key': ['Europe', 'Japan', 'USA'],
        's': [50, 50, 200]
    })
    
    alt.Chart(source).mark_circle(opacity=0.5).transform_lookup(
      lookup='Origin',
      from_=alt.LookupData(df2, key='key', fields=['s'])    
    ).encode(
        x='Horsepower',
        y='Miles_per_Gallon',
        color='Origin',
        size =alt.Size('s:N', title='Size')
    )
    

    enter image description here