St. Bar_chart

Hi!

Is there a way to plot st.bar_chart with sum() or count() on y-axis (like in altair)?
I’ve tried df.groupby and set_index, but it doesnt make sense.
Thanks!

Hello @Saveliy_Borkov,

While Streamlit provides utility functions for plotting like st.line_chart, they actually use Altair under the hood. For more control on your chart, you’re free to pass an Altair plot chart into st.altair_chart, something like :

import altair as alt
from vega_datasets import data
import streamlit as st

source = data.movies.url

chart = alt.Chart(source).mark_bar().encode(
    alt.X("IMDB_Rating:Q", bin=True),
    y='count()',
)
st.altair_chart(chart)

Fanilo

Thanks @andfanilo , but when i plot st.bar_chart it’s more interactive (zoom,moving,etc.). Can i somehow do it in atair?

Yup. Doing that from memory and not tested, the following should do the trick for now:

chart = alt.Chart(source).mark_bar().encode(
    alt.X("IMDB_Rating:Q", bin=True),
    y='count()',
).interactive()
st.altair_chart(chart)

@andfanilo it actually doesnt help, sry. I did that:
scales = alt.selection_interval(bind='scales')

    x_value = st.selectbox('Choose x value',filtered_df.columns)

    y_value = st.selectbox('Choose y value',y_values)

    graph = alt.Chart(filtered_df,title=y_value + ' по ' + x_value).mark_bar(color="#00336E").encode(

    x = alt.X(x_value+':O',axis = alt.Axis(title='')),

    y = alt.Y(y_value, axis=None)).add_selection(scales).interactive()

st.altair_chart((graph).configure_view(strokeOpacity=0).configure_title(fontSize=12).properties(width=700, height=410))

The interactive() is a replacement for scales = alt.selection_interval(bind='scales');...chart.add_selection(scales), as specified in the docs :

Because this is such a common pattern, Altair provides the Chart.interactive() method which creates such a selection more concisely.

I’m not really sure what happens if you call both of them, unfortunately I don’t have a Python on this computer to test further. Also not sure if interactive() needs to be before any configuration part configure_view/title, you will also need to verify the order of the calls in the docs.

If you have some time, you can delve into the interactive charts examples. Altair can get tricky sometimes and the best resource I know to debug them are those examples :wink:

1 Like