Search code examples
data-visualizationaltairgrouped-bar-chart

Configuring the Title and Axes for an Altair Graph


I was recently learning how to use Altair to create graphs, and had some trouble customizing the title and axes. My code for the graph currently looks like:

chart = Chart(data).mark_bar().encode(
    column='Cell Type',
    x='Truth/Pred',
    y='03',
    color='Truth/Pred',
).properties(
    title='Truth vs Predictions for Cell Type Percentages'
).configure_axisBottom(
    disable = True
).configure_axisTop(
    # labelPadding = 100
    orientation = "bottom"
).configure_axisY(
    title = "Cell Type Percentages"
)

chart.display()

and the chart looks like so: Chart generated by code above

I had a few questions.

Is there a way to center the title?

Second, I was trying to set the Y axis to "Cell type percentages", but there seems to be no Y axis, and I'm not sure why.

Lastly, I'm trying to bring the top axis to the bottom and either space the labels out a bit, or rotate them so they don't overlap with each other. However, configuring the axisTop parameter does not seem to affect the Cell Type axis at all! I'm not sure why this is the case either.

I tried following the answer of this stack overflow question: Link to Relevant Question

but I always got errors stating that "additional properties are not allowed", so I'm not sure if they discontinued the use of configuring properties in constructors.

Any help is appreciated. Thank you!


Solution

  • There are some issues with the alignment of headers, due to this Vega-Lite bug https://github.com/vega/vega-lite/issues/5547. However, the following snippet should do most of what you want:

    import altair as alt
    from vega_datasets import data
    
    
    source = data.barley
    
    # Create a centered title
    title = alt.TitleParams('A centered title', anchor='middle')
    alt.Chart(source.url, title=title).mark_bar().encode(
        x=alt.X('year:O', title=''),
        # It is usually easier to specify custom titles like this
        y=alt.Y('sum(yield):Q', title='My custom Y title'),
        color=alt.Color('year:N', title=''),
        # Changing the header of the faceted column controls label location
        column=alt.Column('site:N', title='', header=alt.Header(labelOrient='bottom', labelAngle=-45, labelAlign='right'))
    )
    

    enter image description here