Search code examples
python-3.xaltair

Python Altair, query for current axis limits


I know how to set axis limits and whatnot, but how do I query for currently used axis limits?


Solution

  • I don't think this is possible unless you specifically set an axis limit first:

    import altair as alt
    from vega_datasets import data
    
    source = data.cars.url
    
    chart = alt.Chart(source).mark_circle().encode(
        x='Horsepower:Q',
        y='Miles_per_Gallon:Q',
    )
    
    chart.to_dict()
    
    {'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}},
     'data': {'url': 'https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json'},
     'mark': 'circle',
     'encoding': {'x': {'field': 'Horsepower', 'type': 'quantitative'},
      'y': {'field': 'Miles_per_Gallon', 'type': 'quantitative'}},
     '$schema': 'https://vega.github.io/schema/vega-lite/v5.2.0.json'}
    

    If you set the domain, you can see it in the spec:

    chart = alt.Chart(source).mark_circle().encode(
        x=alt.X('Horsepower:Q', scale=alt.Scale(domain=[0, 250])),
        y='Miles_per_Gallon:Q',
    )
    
    chart.to_dict()
    
    {'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}},
     'data': {'url': 'https://cdn.jsdelivr.net/npm/vega-datasets@v1.29.0/data/cars.json'},
     'mark': 'circle',
     'encoding': {'x': {'field': 'Horsepower',
       'scale': {'domain': [0, 250]},
       'type': 'quantitative'},
      'y': {'field': 'Miles_per_Gallon', 'type': 'quantitative'}},
     '$schema': 'https://vega.github.io/schema/vega-lite/v5.2.0.json'}
    

    and get it via chart.to_dict()['encoding']['x']['scale']['domain'].