Search code examples
pythonstreamlitaltair

Streamlit Altair Bar chart Y axismax min


According to this answer, I'm suppose to use scale = alt.Scae(domain=[0,1.4]) to scale the axis to my preference. But when I do it, the entire bar chart moves lower, hiding the entire x-axis. Why is that?

This is when I'm doing:

    chart_df = alt.Chart(agg_df).mark_bar().encode(
        y=alt.Y('rsi_value'
                ),
        x=alt.X('idx', sort='y'),
        color='type'
    )
    st.altair_chart(chart_df)

enter image description here

When I am doing this, I am able to control the max value to 60.

    chart_df = alt.Chart(agg_df).mark_bar().encode(
        y=alt.Y('rsi_value', scale=alt.Scale(domain=[0, 60])
                ),
        x=alt.X('ticker_idx', sort='y'),
        color='type'
    )
    st.altair_chart(chart_df)

enter image description here

But when I do this:

    chart_df = alt.Chart(agg_df).mark_bar().encode(
        y=alt.Y('rsi_value', scale=alt.Scale(domain=[20, 60])
                ),
        x=alt.X('ticker_idx', sort='y'),
        color='type'
    )

The entire X-axis disappears.

enter image description here

I am just trying to make the bar heights more differentiable...any ideas?


Solution

  • You can use clamp=True in alt.Scale:

    chart_df = alt.Chart(agg_df).mark_bar().encode(
        y=alt.Y('rsi_value', scale=alt.Scale(domain=[20, 60], clamp=True)),
        x=alt.X('ticker_idx', sort='y'),
        color='type'
    )
    

    A minimal working example to show the difference:

    import altair as alt
    import pandas as pd
    import streamlit as st
    
    source = pd.DataFrame({
        'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
        'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
    })
    
    cols = st.columns([1, 1])
    
    with cols[0]:
        st.header("With clamp=False")
        chart_df_0 = alt.Chart(source).mark_bar().encode(
            y=alt.Y('b', scale=alt.Scale(domain=[20, 60], clamp=False)),
            x=alt.X('a', sort='y'),
            
        )
    
        st.altair_chart(chart_df_0)
    
    
    with cols[1]:
        st.header("With clamp=True")
        chart_df_1 = alt.Chart(source).mark_bar().encode(
            y=alt.Y('b', scale=alt.Scale(domain=[20, 60], clamp=True)),
            x=alt.X('a', sort='y'),
            
        )
    
        st.altair_chart(chart_df_1)
    

    enter image description here