我想创建两个叠加的图表,但有两个图例。一个图表使用带有一个调色板的矩形,第二个图表使用第二个调色板显示圆圈。这应该很简单,但有些地方是错误的。我只得到一个传说。我还希望图例可以选择。这是一个独立的 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)
答案 0 :(得分:0)
Altair/Vega-Lite 在可能的情况下,默认情况下将图表之间的现有比例合并为一个图例,以实现更紧凑的布局。当比例相互独立并且应该在单独的图例中表示时,您需要手动解决它们,在您的情况下它看起来像这样
chart.resolve_scale(color='independent')