Calmcode - altair: types

Assign type information in Altair Python.

1 2 3 4 5 6 7 8 9

Adding Types to a Chart in Altair

You can add type information to an altair chart. You can declare time-based features, nominal features and quantitative features. Specifying the color is also easy.

The bar chart at the end of this video is created via;

(alt.Chart(plot_df)
  .mark_bar(color='lightblue')
  .encode(x='date:T', y='births:Q', color='month:N', tooltip=['date', 'births'])
  .properties(height=200))

Encoding :T, :Q, :O and :N

In short the types in Altair allow you to declare:

  • :T a datetime-like field
  • :Q a quantitative field
  • :O an ordered categorical field
  • :N a non-ordered categorical field

Setting these types typically has consequence for how the .encode() method will render the end-result. It can handle type-casting, but you may want to resort to methods like alt.Color if you want full control over how legends are rendered.