【问题标题】:Plot multi-series Dataframe using Streamlit + Altair使用 Streamlit + Altair 绘制多系列数据框
【发布时间】:2021-09-02 23:53:07
【问题描述】:

我有以下 DF elo_df

date        Person1 Person2 Person3 Person4 Person5 Person6                     
2020-12-31  1500    1500    1500    1500    1500    1500
2021-01-01  1480    1506    1506    1500    1506    1500
2021-01-06  1513    1495    1495    1490    1515    1490
2021-01-08  1506    1502    1502    1490    1508    1490

我想使用 Altair 绘制它,并让它可缩放和交互。此外,我希望能够将 Y 域设置为 [1350, 1600]。我有一份players_names=["Person1",..., "Person6"] 的列表,我想使用它,以防还有一个人。

这是我目前所做的

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

[...part where I obtain elo_df...]

k = alt.Chart(elo_df.reset_index()).transform_fold(
    players_names).mark_line().encode(
        alt.X('date'),
        alt.Y('value', scale=alt.Scale(domain=[1350, 1600])),
        color='variable',
    )

    st.altair_chart(k)

这导致我出现以下错误: ValueError: variable encoding field is specified without a type; the type cannot be inferred because it does not match any column in the data.

即使在阅读文档之后,我也没有完全弄清楚transform_fold 的原因以及接下来如何使用它,所以任何新的解释方式都将不胜感激。

【问题讨论】:

  • 考虑更改数据框的格式。每人有一列似乎不是正确的数据格式。试试{"date": "2020-12-31", "value": 1500, "person": 1} 之类的东西。为 x 选择日期,为 y 选择值,为颜色选择人。通常color 会将其分成单独的行来绘制。

标签: python pandas plot altair streamlit


【解决方案1】:

Altair 使用 pandas 来确定绘制数据时要使用的数据类型。对于不属于 pandas 数据框的任何数据,例如来自 URL 的数据或来自转换的列,您需要explicitly specify what type the data is

import altair as alt
import pandas as pd


elo_df = pd.read_clipboard()
players_names=elo_df.filter(like='Person').columns.tolist()
chart = alt.Chart(elo_df.reset_index()).transform_fold(
    players_names).mark_line().encode(
        alt.X('date:T'),
        alt.Y('value:Q', scale=alt.Scale(domain=[1350, 1600])),
        color='key:N',
    )

chart

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多