pythonaltairtypesetting

Saving Altair charts without white space around them


I'm using Altair charts in my academic papers.

Conference papers have strict page limits. Naturally, I want to use all of the space I decide to assign for a figure for the actual chart and not for the white space around it. White space is automatically added around figures by the Latex typesetting framework, and authors are warned against tampering with it, so I don't need additional white space inside of my images.

Currently, my method is that every time I generate a chart I want to paste into my paper, I first manually remove the white space around the png image using KolourPaint. This is tedious and error-prone, of course.

Is there a way to configure Altair to generate only the minimum amount of white space around a chart? If it matters, vertical white borders matter more for me.

Altair chart saved as png: enter image description here

Image after manual removal of white space around the chart: enter image description here

(you might need to download the two images and open them in an image viewer to see the white border more clearly)


Solution

  • The space around Altair charts is controlled by Vega's view.padding property, which can be set in the renderer:

    alt.renderers.set_embed_options(
        padding={"left": 0, "right": 0, "bottom": 0, "top": 0}
    )
    

    The default padding is 5 on each side.

    For example, using the fivethirtyeight theme to better display the padding, you can create a chart like this:

    import altair as alt
    alt.renderers.set_embed_options(
        theme="fivethirtyeight",
        padding={"left": 0, "right": 0, "bottom": 0, "top": 0}
    )
    
    # load a simple dataset as a pandas DataFrame
    from vega_datasets import data
    cars = data.cars()
    
    alt.Chart(cars).mark_point().encode(
        x='Horsepower',
        y='Miles_per_Gallon',
        color='Origin',
    )
    

    enter image description here