Home  >  Article  >  Backend Development  >  Altair Plots in Streamlit: How to add a legend?

Altair Plots in Streamlit: How to add a legend?

WBOY
WBOYforward
2024-02-09 13:30:041288browse

Streamlit 中的 Altair 绘图:如何添加图例?

Question content

I am using streamlit and need altair for drawing (because of the interpolation option available).

Given this simple code:

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

data = pd.DataFrame({"x": [0, 1, 2, 3], "y": [0, 10, 15, 20], "z": [10, 8, 10, 1]})

base = alt.Chart(data.reset_index()).encode(x="x")

chart = alt.layer(
    base.mark_line(color="red").encode(y="y", color=alt.value("green")),
    base.mark_line(color="red").encode(y="z", color=alt.value("red")),
).properties(title="My plot",)

st.altair_chart(chart, theme="streamlit", use_container_width=True)

This results in this graph:

What is the correct way to add a legend next to a figure?

In the documentation I see the legend option as being part of "color", but this always seems to be about visualizing another dimension. In my case, I just want to draw different lines and plot the legend with their respective colors.


Correct answer


Convert your data to long data frame format. This format is more suitable for creating legends in altair because each row is associated with a category. Then use this category for color coding:

import streamlit as st
import altair as alt
import pandas as pd
alt.renderers.enable("html")

# Your data
data = pd.DataFrame({
    "x": [0, 1, 2, 3],
    "y": [0, 10, 15, 20],
    "z": [10, 8, 10, 1]
})


# Transform data to long format
data_long = pd.melt(data, id_vars=['x'], value_vars=['y', 'z'], var_name='category', value_name='y,z')

# Create an Altair chart
chart = alt.Chart(data_long).mark_line().encode(
    x='x',
    y='y,z',
    color='category:N'  # Use the category field for color encoding
).properties(
    title="My plot"
)


st.altair_chart(chart, use_container_width=True)

Output:

The above is the detailed content of Altair Plots in Streamlit: How to add a legend?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete