简体   繁体   中英

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:

条形图示例

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM