79224927

Date: 2024-11-26 00:13:04
Score: 0.5
Natty:
Report link

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.

Chart with stroked background

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
Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: kgoodrick