【问题标题】:How to plot recs and circles with two legends with Altair?如何用 Altair 绘制带有两个图例的 recs 和 circles?
【发布时间】:2021-09-02 08:13:52
【问题描述】:

我想创建两个叠加的图表,但有两个图例。一个图表使用带有一个调色板的矩形,第二个图表显示带有第二个调色板的圆圈。这应该很简单,但是有问题。我只得到一个传奇。我还希望图例可以选择。这是一个独立的 MWE,代表了一个更复杂的用例。在代码下方,我展示了代码生成的图像:单个图例、单个调色板。这是预期的行为还是某种错误?任何见解都值得赞赏。谢谢!

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

# Demonstrate two categorical legends with selection_multi.
# There appears to be a bug when using shift-click on one menu, then the other.

def drawPlot():

    x1 = [1, 2, 3]
    y1 = [1, 2, 3]
    x2 = [4, 5, 6]
    y2 = [4, 5, 6]
    df = pd.DataFrame({'x1':x1, 'y1':y1, 'x2':x2, 'y2':y2})

    palette1 = alt.Color('x1:N',
        scale=alt.Scale(
          domain=[1, 2, 3],
          range=['lightgreen', 'darkgreen', 'yellow'],
        )
    )
    palette2 = alt.Color('x2:N',
        scale=alt.Scale(
          domain=[4, 5, 6],
          range=['lightblue', 'darkblue', 'purple'],
        )
    )

    select1 = alt.selection_multi(fields=['x1'], bind='legend')
    select2 = alt.selection_multi(fields=['x2'], bind='legend')

    nodes1 = alt.Chart(df).mark_rect(
        width=20, height=20,
    ).encode(
        x = 'x1:N',
        y = 'y1:N',
        color = palette1,
    ).add_selection(
        select1
    )

    nodes2 = alt.Chart(df).mark_circle(
        width=20, height=20, size=1200,
    ).encode(
        x = 'x2:N',
        y = 'y2:N',
        color = palette2,
    ).add_selection(
        select2
    )

    full_chart = (nodes1 + nodes2).properties(
        height=500,
        width=1000,
    )

    return full_chart

#----------------------------------------------------------------
if __name__ == "__main__":
    chart = drawPlot()
    st.altair_chart(chart, use_container_width=True)

【问题讨论】:

    标签: python selection altair


    【解决方案1】:

    默认情况下,Altair/Vega-Lite 会在可能的情况下将图表之间的现有比例合并到一个图例中,以实现更紧凑的布局。当比例相互独立并且应该在单独的图例中表示时,您需要手动解决它们,在您的情况下看起来像这样

    chart.resolve_scale(color='independent')
    

    You can read more on this page in the docs.

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多