Search code examples
pythonplotbar-chartaxis-labelsaltair

Adjusting Labels of Altair Grouped Bar Chart


I have this dataframe called table:

TERM                        Bitcoin       S&P500    Real Estate Gold
0   High-Inflation/ Short term  3097.94       -3700.78  761.23      6512.71
1   High-Inflation/ Mid term    —             -3080.01  -8434.66    3242.40
2   High-Inflation/ Long term   —             -2089.25  -9117.96    8174.43
3   Low-Inflation/ Short term   780200.00     -273.71   1824.72     2214.51
4   Low-Inflation/ Mid term     21013600.00   5331.40   35810.58    -2879.37
5   Low-Inflation/ Long term    978017143.00. 15045.41  35895.81    861.90

And have generated a graph with this code:

from itertools import product
alt.Chart(table).transform_fold(
    ["Bitcoin", "S&P500", "Real Estate", "Gold"], as_=["key", "value"]
).mark_bar().encode(
    x="key:N",
    y=alt.Y("value:Q", scale=alt.Scale(type='symlog'),
           axis=alt.Axis(values=[0] + [10**x * y for (x, y) in product(range(1, 10, 1), (1, -0.01))])),
    color="key:N",
    column="TERM",
)

However as you can see the labels at the top are smushed together. I am not sure how to make those more visually appealing, and also how to remove the key label on the x-axis of each graph:

chart


Solution

  • You can remove the x title by setting title=None in the x encoding. You can add a line break to the problematic strings by replacing them with a list of lines. For example:

    table['TERM'] = table['TERM'].str.split(' ', 1)
    alt.Chart(table).transform_fold(
        ["Bitcoin", "S&P500", "Real Estate", "Gold"], as_=["key", "value"]
    ).mark_bar().encode(
        x=alt.X("key:N", title=None),
        y=alt.Y("value:Q", scale=alt.Scale(type='symlog'),
               axis=alt.Axis(values=[0] + [10**x * y for (x, y) in product(range(1, 10, 1), (1, -0.01))])),
        color="key:N",
        column="TERM"
    )
    

    enter image description here