Combining string and aggregate function within bar chart label in Altair

Viewed 352

I have made two interactive linked histograms with crossfiltering using Altair. I have created labels over each bar with the sum of the filtered items by using mark_text(). Below is an image of the linked charts:

enter image description here

I would like learn how to concatenate a string in the label so that it would look something like: 'error: 481.1'. This is the relevant code snippet:

crossfilter = alt.selection(type='interval', encodings=['x'])

tick_up = alt.Chart().transform_filter(crossfilter).mark_tick(color='black').encode(
                                x = x, 
                                y = alt.Y(plus_error+':Q', aggregate='sum'))
text = tick_up.mark_text(
        align='left',
        baseline='middle',
        dx=12  
    ).encode(text='sum(error):Q')

When I try to change .encode(text='sum(error):Q') to something like .encode(text='"error": sum(error):Q'), it throws me an error, is there a simple way to do this? I have also tried using transform_calculate, but I need something adapts to what is being selected by crossfilter.

I would also like to learn how to create a label with multiple lines, for example:

curr_error: 123.1 
previous_error: 110
1 Answers

You can use + in transform_calculate to concatenate a string and a number. I believe you will also need transform_joinaggregate to have your sum accessible in the calculation transformation. Something like this:

import altair as alt
from vega_datasets import data

source = data.cars()

chart = alt.Chart(source).mark_text(align='left', dx=2).encode(
    x='sum(Horsepower)',
    y='Origin',
    text='label:N'
).transform_joinaggregate(
    sum_hp = 'sum(Horsepower)',
    groupby=['Origin']
).transform_calculate(
    label = "'error: ' + datum.sum_hp"
)

chart.mark_bar() + chart

enter image description here

This also works with a selection, but make sure the transform_filter is before the other transforms so that only the selected data points are used for the calculations:

import altair as alt
from vega_datasets import data

source = data.cars()
brush = alt.selection_interval()

scatter = alt.Chart(source).mark_point().encode(
    x='Horsepower',
    y='Weight_in_lbs',
    color='Origin'
).add_selection(
    brush
)

bars = alt.Chart(source).mark_text(align='left', dx=2).encode(
    x='sum(Horsepower)',
    y='Origin',
    text='label:N'
).transform_filter(
    brush
).transform_joinaggregate(
    sum_hp = 'sum(Horsepower)',
    groupby=['Origin']
).transform_calculate(
    label = "'error: ' + datum.sum_hp"
)

scatter & bars.mark_bar() + bars

enter image description here

Related