I'm trying to use multi-line labels for a stacked bar chart, but running into the problem replicated with sample code below. Trying to use the regular textwrap lists for axis labels results in broken stacked bar charts as seen in the image. Can anyone tell me why or if there is a work-around?
Altair version 5.0.0
import altair as alt
from vega_datasets import data
import textwrap
source = data.barley()
source['multiline_label'] = source['variety'].apply(textwrap.wrap, args=[5])
alt.Chart(source).mark_bar().encode(
x=alt.X('sum(yield)').stack("normalize"),
y='multiline_label',
color='site'
)
After some playing around and a lot of rooting through the documentation, I managed to find a workaround. After splitting the labels with textwrap.wrap, you can re-join them on some separator (I used '_'). Then, you can use labelExpr within an axis configuration to re-split the labels on that separator. Revised code and result below.
import altair as alt
from vega_datasets import data
import textwrap
source = data.barley()
source['multiline_label'] = source['variety'].apply(textwrap.wrap, args=[5])
source['multiline_label'] = source['multiline_label'].apply(lambda x: '_'.join(x))
alt.Chart(source).mark_bar().encode(
x=alt.X('sum(yield)').stack("normalize"),
y='multiline_label:N',
color='site'
).configure_axisY(
labelExpr = 'split(datum.label, "_")'
)