How to add a nested X axis with streamlit

Summary

I’m trying to make a graph like the one attached. Essentially i have date and time in two separate columns in a data frame along with a forecast column. I want to have a nested x axis such that date and time show up on the axis but nest like this. Any idea how to do this with streamlit? Thanks in advance

1 Like

Hi @SilentCoder and welcome to the community! :raised_hands:

I did play around and this is where I got up to.

import altair as alt
import pandas as pd
import streamlit as st

data = {
    'Date': ['2023-09-18', '2023-09-18', '2023-09-18', '2023-09-19', '2023-09-19', '2023-09-19'],
    'Time': ['08:00', '12:00', '16:00', '08:00', '12:00', '16:00'],
    'Forecast': [100, 200, 150, 180, 220, 170]
}
df = pd.DataFrame(data)

chart = alt.Chart(df).mark_bar().encode(
    x='Time:O',
    y='Forecast:Q',
    column='Date:O',
    color=alt.Color('Forecast:Q', scale=alt.Scale(scheme='blues'))
).properties(
    width=100,
    height=150,
)

st.altair_chart(chart)

Recording 2023-09-19 at 08.52.20 (1)

You may need to tweak the code a bit more to get a line chart, but hopefully, that helps you get started! :slight_smile:

Best,
Charly

1 Like

Thank you so much. This is super helpful. I appreciate it.

@SilentCoder ,

Expanding on @Charly_Wargnier solution, you could use a lambda expression on your Dataframe to combine the fields and pass those to Altair.

import altair as alt
import pandas as pd
import streamlit as st

data = {
    "Date": [
        "2023-09-18",
        "2023-09-18",
        "2023-09-18",
        "2023-09-19",
        "2023-09-19",
        "2023-09-19",
    ],
    "Time": ["08:00", "12:00", "16:00", "08:00", "12:00", "16:00"],
    "Forecast": [100, 200, 150, 180, 220, 170],
}
df = pd.DataFrame(data)
df["TS"] = df.apply(lambda x: f'{x["Date"]} {x["Time"]}', axis=1)
chart = (
    alt.Chart(df)
    .mark_line()
    .encode(
        x="TS:O",
        y="Forecast:Q",
        # color=alt.Color("Forecast:Q", scale=alt.Scale(scheme="blues")),
    )
)
st.altair_chart(chart, use_container_width=True)
1 Like

Nice!

Thanks, Carlos!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.