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
Good question! With the following code your result will look as such:

This is produced using the following code:
import altair as alt
import pandas as pd
# Data
data = pd.DataFrame([
{"a": "A", "b": -28},
{"a": "B", "b": 55},
{"a": "C", "b": -33},
{"a": "D", "b": 91},
{"a": "E", "b": 81},
{"a": "F", "b": 53},
{"a": "G", "b": -19},
{"a": "H", "b": 87},
{"a": "I", "b": 52}
])
# Bar chart
bars = alt.Chart(data).mark_bar().encode(
y=alt.Y("a:N"),
x=alt.X("b:Q").scale(padding=20),
color=alt.when(alt.datum['b'] > 0).then(alt.value("#003865")).otherwise(alt.value("#5E8AB4"))
)
# Text labels
text = alt.Chart(data).mark_text(
align=alt.expr(alt.expr.if_(alt.datum['b'] < 0, 'right', 'left')),
dx=alt.expr(alt.expr.if_(alt.datum['b'] < 0, -2, 2))
).encode(
y="a:N",
x="b:Q",
text="b:Q"
)
bars + text
This is based on this Vega-Lite example, but there is not yet an Vega-Altair example that showcase this possibility, let me raise there as well! Thanks for asking this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With