Search code examples
pythonaltair

Bold some of the x-labels with alt.condition in Altair plot


How shall I make some of the x-labels bold with alt.condition? For example with the following code, I try to make the x-label 'C' bold, which is corresponding to the max value 9 on the y-axis.

df = pd.DataFrame({'Name': ['A', 'B', 'C', 'D'], 'Value': [1, 5, 9, 2]})

alt.Chart(df).mark_line().encode(
    x = alt.X(
        'Name:N',
        axis = alt.Axis(
            labelFontWeight = alt.condition(alt.datum.Value == df.Value.max(), alt.value(800), alt.value(300))
        )
    ),
    y = 'Value:Q'
)

It's weird that it always goes to the if-false value, not matter how I change the predict.

Make x-label 'C' bold


Solution

  • I am not sure if you can do that directly in Altair/Vega-Lite, but you could compute the Name for the max Value and compare similar to what was suggested in the comments but slightly more automated using f-strings:

    import pandas as pd
    import altair as alt
    
    
    df = pd.DataFrame({'Name': ['A', 'B', 'C', 'D'], 'Value': [1, 5, 9, 2]})
    max_name = df['Name'][df['Value'].argmax()]
    
    alt.Chart(df).mark_line().encode(
        x=alt.X(
            'Name:N',
            axis = alt.Axis(
                # datum.label also works
                labelFontWeight=alt.condition(f"datum.value == '{max_name}'", alt.value(800), alt.value(300))
            )
        ),
        y='Value:Q'
    )
    

    enter image description here