timthoe
timthoe

Reputation: 95

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.

Upvotes: 3

Views: 3228

Answers (2)

Hassen Morad
Hassen Morad

Reputation: 47

I'm not sure if this exactly what you're looking for since you mentioned wanting to create a theme, but you can recreate the look of the UI theme by adding text to your chart via mark_text().

Here's an example:

df = pd.DataFrame({'col1':[0,1,2,3,4,5], 'col2':[0,1,2,3,4,5]})
text_df = pd.DataFrame({'col1':[0], 'col2':[0], 'col3':['title']})

line = alt.Chart(df).mark_line().encode(x='col1', y='col2')
text = alt.Chart(text_df.query('col1 == 0')).mark_text(dx=-60, dy=-400, fontSize=24, font='Lato').encode(x='col1', y='col2', text='col3')
line + text

This is the resulting chart:

enter image description here

Upvotes: 1

jakevdp
jakevdp

Reputation: 86443

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.

Upvotes: 6

Related Questions