Jose Manuel
Jose Manuel

Reputation: 45

How to center the title in a grouped bar chart with altair

I'm trying to center the title in a grouped bar chart.

By reading the docs (), I thought I could manage to do this by specifying the orient and anchor parameters in the configure_title method.

This however does not seem to be working for me. I tried several values for the anchor parameter but it looks like it is not applied and sticks to its default value.

Is there something I'm missing?

I am working with the version 2.4.1 of altair.

import altair as alt
import pandas as pd


# dataset
df = pd.DataFrame([[1, 'A', 'G1'],
                   [2, 'A', 'G2'],
                   [5, 'B', 'G1'],
                   [10, 'B', 'G2'],
                   [4, 'C', 'G1'],
                   [9, 'C', 'G2'],
                   [1, 'D', 'G1'],
                   [1, 'D', 'G2'],
                   [4, 'E', 'G1'],
                   [9, 'E', 'G2'],
                   [8, 'F', 'G1'],
                   [1, 'F', 'G2'],
                   [2, 'G', 'G1'],
                   [3, 'G', 'G2'],
                   [2, 'H', 'G1'],
                   [1, 'H', 'G2'],
                   [3, 'I', 'G1'],
                   [8, 'I', 'G2'],
                   [7, 'J', 'G1'],
                   [5, 'J', 'G2'],
                  ], columns=['Count', 'Category', 'Group'])


chart = alt.Chart(df, title=f"Count of categories in each group",
         width=50, height=600).mark_bar().encode(   column=alt.Column('Category:O'),
                                                    color=alt.Color('Group', type='nominal', scale=alt.Scale(range=['#1f77b4', '#2ca02c'])),
                                                    x=alt.X(field="Group", type="nominal",
                                                            axis=None,
                                                            title="Category",
                                                           ),
                                                    y=alt.Y(field="Count", type="quantitative",
                                                            axis=alt.Axis(title="Number of records",
                                                                          titlePadding=10.0),
                                                           ),
)
chart = chart.configure_title(fontSize=20, offset=5, orient='top', anchor='middle')

# display the chart
chart

Chart with the title top left instead of top middle

The title remains at the top left instead of being at the top middle.

Upvotes: 0

Views: 4700

Answers (1)

jakevdp
jakevdp

Reputation: 86353

This is an issue in Vega-Lite 2 that has been fixed in Vega-Lite 3. Once you update to Altair version 3, it should work as expected without any change to your code: enter image description here

Upvotes: 1

Related Questions