Search code examples
pythonaltairgraphing

Cannot add text on repeated bar graphs - Altair


I created a repeated bar graph with altair but I cannot seem to add the same text (column = Rank) to the bars on all bar charts. This is the error message I get: 'RepeatChart' object has no attribute 'mark_text'

chart1 = alt.Chart(merged, width=500, height=300).mark_bar().encode(
    alt.X("City", type='ordinal', sort="-y"),
    alt.Y(alt.repeat("column"), type='quantitative'),
    alt.Color('City', legend=None, scale=alt.Scale(scheme='tableau20'))).repeat(
    column=['Cost of a bottle of water(City)', 'Pollution(Index score) (City)', 'Annual average hours worked', 
            'Outdoor activities(City)','Number of take out places(City)', 'Cost of a monthly gym membership(City)', 
            'Cost of Living Index', 'Rent Index', 'Cost of Living Plus Rent Index', 'Groceries Index', 
            'Restaurant Price Index','Local Purchasing Power Index'])
chart1  

text = chart1.mark_text(baseline='middle',
    dx=20,
    angle=340,
    color='black',
).encode(
    text=alt.Text('Rank'))

chart1 + text

Solution

  • You cannot change the mark of a RepeatChart. You need to create the layer first and then use repeat on the layered chart. Something like this:

    chart1 = alt.Chart(merged, width=500, height=300).mark_bar().encode(
        alt.X("City", type='ordinal', sort="-y"),
        alt.Y(alt.repeat("column"), type='quantitative'),
        alt.Color('City', legend=None, scale=alt.Scale(scheme='tableau20')))
    
    text = chart1.mark_text(baseline='middle',
        dx=20,
        angle=340,
        color='black',
    ).encode(
        text=alt.Text('Rank'))
    
    (chart1 + text).repeat(
        column=['Cost of a bottle of water(City)', 'Pollution(Index score) (City)', 'Annual average hours worked', 
                'Outdoor activities(City)','Number of take out places(City)', 'Cost of a monthly gym membership(City)', 
                'Cost of Living Index', 'Rent Index', 'Cost of Living Plus Rent Index', 'Groceries Index', 
                'Restaurant Price Index','Local Purchasing Power Index'])
    

    Here is a complete reproducible example:

    import altair as alt
    from vega_datasets import data
    
    
    source = data.cars()
    
    
    c = alt.Chart(source).mark_circle().encode(
        x=alt.X('Weight_in_lbs:Q', title=''),
        y=alt.Y(alt.repeat(), type='quantitative'),
    )
    
    (c + c.mark_line()).repeat(['Horsepower', 'Acceleration'])
    

    enter image description here