Altair Plots in Streamlit: How to add a legend?

WBOY
Release: 2024-02-09 13:30:04
forward
1286 people have browsed it

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)
Copy after login

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)
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!