4

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!

p_mo
  • 67
  • 2
  • 10

1 Answers1

5

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

joelostblom
  • 43,590
  • 17
  • 150
  • 159
  • Thank you for answer! I have changed the code to be more like yours, and most of the chart details looks correct, but the graph "Cell Type" labels still remain on the top of the graph. Do you know why this might be the case? – p_mo Jun 21 '22 at 06:26
  • @p_mo I think that is a bug with altair version <=4.2.0 that was fixed in the development version which is what I was using for the answer. – joelostblom Jun 22 '22 at 15:59