In addition to Joel's suggestion of using a background box, I have also had good results adding a copy of the text with a stroke behind the main text. This automatically adjusts the background to the right size.
import altair as alt
import pandas as pd
# Example data
data = pd.DataFrame({
'category': ['A', 'B', 'C', 'D'],
'value': [10, 20, 15, 25]
})
# Base chart with gridlines
chart = alt.Chart(data).mark_bar().encode(
x='value:Q',
y=alt.Y('category:N', axis=alt.Axis(grid=True, gridWidth=2, gridColor='darkslategray'))
)
text = alt.Chart(data).mark_text(
align='left',
baseline='middle',
color='black',
dx=3 # Nudge the text to the right
).encode(
x='value:Q',
y='category:N',
text=alt.Text('value:Q')
)
text_background = text.mark_text(
align='left',
baseline='middle',
stroke='white',
strokeWidth=5,
strokeJoin='round',
dx=3
)
# Combine the charts
final_chart = chart + text_background + text
final_chart