Streamlit bar chart with different color for each label

I have a DataFrame that contains two columns:

  • Nucleotide (ordinal, only unique values)
  • Similarities (quantative, count of specific Nucleotide)

I want to plot an interactive bar chart using Streamlit, where each Nucleotide will have different color, like on the example below:

Example bar chart

I know how to do it using matplotlib or seaborn, but these figures are not interactive. Also my approach using vega-lite does not work, because the 'c' argument for the colormap cannot refer to the axis being already used on the plot.

st.vega_lite_chart(df, {
     'mark': {'type': 'bar', 'tooltip': True},
     'encoding': {
         'x': {'field': 'Nucleotide', 'type': 'ordinal'},
         'y': {'field': 'Similarities', 'type': 'quantitative'},
         'color': {'field': 'Nucleotide', 'type': 'ordinal'},
     },
 })

Do you maybe have some other ideas?


Solution 1:

Altair is a great choice here in my view. It comes out of the box with streamlit and creates very nice looking and interactive charts. Bascially you have to create a Chart object, pass in the data that you want to plot, and use the column names for things like x,y or color. For your example, the code would read like

import altair as alt
import streamlit as st

chart = (
    alt.Chart(data)
    .mark_bar()
    .encode(
        alt.X("Nucleotide:O"),
        alt.Y("Similarities"),
        alt.Color("Nucleotide:O"),
        alt.Tooltip(["Nucleotide", "Similarities"]),
    )
    .interactive()
)
st.altair_chart(chart)

assuming your dataframe is called data and the columns are called "Nucleotide" and "Similarities". This would be a very basic bar chart that you can zoom in and hover over to see a tooltip.