Search code examples
altair

adjusting properties (e.g. width and height) on a layered faceted chart produce a 'data is a required property error'


I'm trying to adjust the width and height of a faceted layered chart. I have these two charts:

bar_chart = alt.Chart().mark_bar().encode(x='x', y='mean(y)')
text_overlay = bar_chart.mark_text().encode(text='mean(y)')

if I try to adjust the width after I layered the chart with:

alt.layer(bar_chart, text_overlay, data=df).facet('z').properties(width=100)

I get a 'data' is a required property error.

I can change the width and height by adjusting one of the original charts with:

bar_chart = alt.Chart().mark_bar().encode(x='x', y='mean(y)').properties(width=100, height=200)

but I'm trying to return this chart as the output of a function, so I'd like to allow the user to adjust the properties outside of the function.

Is there any way around this error that doesn't require to apply the properties to the original charts?

Thank you.


Solution

  • I think you can only use .properties when using facet as an encoding, but that is not compatible with layering. You could use the object oriented syntax to set the property after creation of the faceted layered chart:

    import altair as alt
    import pandas as pd
    
    
    chart = alt.Chart(pd.DataFrame({'x': [1, 2], 'y': ['b', 'a']})).mark_point().encode(x='x', y='y')
    chart_layered = (chart + chart).facet(facet='y')
    chart_layered.spec.width = 100
    chart_layered
    

    enter image description here

    To figure out which these attribues are, you could create a faceted layered chart using .properties the right way and study its dictionary or json output:

    chart = alt.Chart(pd.DataFrame({'x': [1, 2], 'y': ['b', 'a']})).mark_point().encode(x='x', y='y').properties(width=100).facet(facet='y')
    chart.to_dict()
    
    {'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}},
     'data': {'name': 'data-5f40ae3874157bbf64df213f9a844d59'},
     'facet': {'type': 'nominal', 'field': 'y'},
     'spec': {'mark': 'point',
      'encoding': {'x': {'type': 'quantitative', 'field': 'x'},
       'y': {'type': 'nominal', 'field': 'y'}},
      'width': 100},
     '$schema': 'https://vega.github.io/schema/vega-lite/v4.8.1.json',
     'datasets': {'data-5f40ae3874157bbf64df213f9a844d59': [{'x': 1, 'y': 'b'},
       {'x': 2, 'y': 'a'}]}}