Search code examples
vega-litealtair

Aligning chart title with left side of numbers on the y axis


I am trying to make an Altair theme that conforms with our internal guidelines. I found this excellent article that solved most of my issues. However, neither the article nor a search of the documentation has solved the problem of aligning the chart title with the left side of the numbers on the y axis. See the dotted line in Urban institute's theme for visual explanation. The problem is that I do not know the width of the longest number on the y axis. The solutions I have found just hard code an offset for the expected width of the number. However, I have to make a theme that automatically conforms to the standard in all cases. Hints to possible solutions are welcome. I will try them out and post results.


Solution

  • The available title alignment settings for Altair/Vega-Lite are listed here: https://vega.github.io/vega-lite/docs/title.html#params

    The closest thing to what you desire is to set anchor='start' in the title config:

    import altair as alt
    from vega_datasets import data
    cars = data.cars()
    
    alt.Chart(cars).mark_bar().encode(
      x=alt.X('Miles_per_Gallon', bin=True),
      y='count()',
    ).properties(
        title='A bar chart'
    ).configure_title(
        anchor='start'
    )
    

    enter image description here

    Unfortunately, there is no way in the Vega-Lite schema to control the alignment more finely than that. If this is important to your use of Altair/Vega-Lite, I would suggest opening a Vega-Lite feature request.