[Python] Labels for both positive and negative values in Streamlit Altair chart

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to add labels to my altair chart in streamlit but the example codes only work for when the values are either all positive or all negative. I want the labels to be positioned to the left of the bar if it's negative and to the right if it's positive. It doesn't seem to accept alt.condition on align property.

    c = alt.Chart(joint_exposures).mark_bar().encode(
    y='Factor',
    x='Active',
    color=alt.condition(
    alt.datum['Active'] > 0,
    alt.value("#003865"), # The positive color
    alt.value("#5E8AB4") # The negative color
    ),
    tooltip=[
    alt.Tooltip('Factor:N'), # Show category
    alt.Tooltip('Active:Q', format='.4f', title='Active Exposure')
    # Value with 2 decimal places
    ]
    )
    text = c.mark_text(
    baseline='middle',
    color='black',
    align='left',
    dx=5
    ).encode(
    text=alt.Text('Active:Q',
    format=",.3f"
    )
    )
    table_height = 35 * (len(joint_exposures) + 2)
    chart = (c + text).properties(height=table_height).configure_axis(
    labelColor='black',
    titleColor='black'
    ).configure_title(
    color='black'
    ).configure_legend(
    labelColor='black',
    titleColor='black'
    )
    st.altair_chart(chart, use_container_width=True)


    I end up with a chart like this (and the labels are the same color as the bars even though I specified the text to be black): Altair Chart

    Continue reading...

Compartilhe esta Página