Search code examples
pythonaltair

How to install a new font in altair and specifying it in alt.TitleParams


I am wondering if it's possible to install fonts to use in altair to use in alt.TitleParams. For this example, without font specified, I get a default font and size.

import altair as alt
import pandas as pd

source = pd.DataFrame({
    'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
    'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})

alt.Chart(source, title = alt.TitleParams(text = 'Example Chart')).mark_bar().encode(
    x='a',
    y='b'
)

enter image description here

Changing the font size I get the bigger letters:

alt.Chart(source, title = alt.TitleParams(text = 'Example Chart', fontSize=24)).mark_bar().encode(
    x='a',
    y='b'
)

enter image description here

But, when I add a font style, the size doesn't work anymore:

alt.Chart(source, title = alt.TitleParams(text = 'Example Chart'
                                          , fontSize=24
                                          , fontStyle = 'Arial')).mark_bar().encode(
    x='a',
    y='b'
)

enter image description here

And the text looks always the same regardless of what font is specified:

alt.Chart(source, title = alt.TitleParams(text = 'Example Chart'
                                          , fontSize=24
                                          , fontStyle = 'Calibri')).mark_bar().encode(
    x='a',
    y='b'
)

Same thing:

enter image description here

I would like to know how I can display the correct font, not only with standard fonts, but with non-standard ones and how to install them.


Solution

  • fontStyle refers to the style of the font, such as "bold", "italic", etc. If you want to specify a font by name, use the font parameter:

    alt.Chart(
        source,
        title=alt.Title(  # Since altair 5 you can use just Title instead of TitleParams
            text='Example Chart',
            fontSize=24,
            fontStyle='italic',
            font='Times'
        )
    ).mark_bar().encode(
        x='a',
        y='b'
    )
    

    enter image description here