首页 > 解决方案 > 在 Altair 中加入两个图表时控制图例颜色和顺序

问题描述

我很难在图例中获得正确的颜色顺序。

我正在努力达到:

cash: blue
fixed_income: yellow
equity: red

我正在使用以下数据框“dfl”绘制两行三个图表:

  trade_date account owner account_type asset  value  sort_asset
0 2002-01-02  p2_inv    p2          inv  cash    0.0           0
1 2002-01-03  p2_inv    p2          inv  cash    0.0           0
2 2002-01-04  p2_inv    p2          inv  cash    0.0           0

dfl.shape (76824, 7)

我有以下代码:

df_p1 = dfl[dfl['owner'] == 'p1']
df_p2 = dfl[dfl['owner'] == 'p2']

base_p1 = alt.Chart(df_p1).mark_area().encode(
    x=alt.X('trade_date:T', title=""), 
    y=alt.Y('sum(value):Q', stack='normalize', title="Asset Allocation"), 
    color=alt.Color('asset:N', sort=['cash', 'fixed_income', 'equity']),
    order=alt.Order('sort_asset:N', sort='ascending')
).properties(
    width=120,
    height=160
).facet(
    column=alt.Column('account:N'), 
)
base_p2 = alt.Chart(df_p2).mark_area().encode(
    x=alt.X('trade_date:T', title=""), 
    y=alt.Y('sum(value):Q', stack='normalize', title="Asset Allocation"), 
    color=alt.Color('asset:N', sort=['cash', 'fixed_income', 'equity']),
    order=alt.Order('sort_asset:N', sort='ascending')
).properties(
    width=120,
    height=160
).facet(
    column=alt.Column('account:N'),
)

base_p1 & base_p2

当我自己运行 base_p1 或 base_p2 时,我得到了正确的图例。但是当我使用 & 我将它们连接在一起时,我的图例和颜色变为:

cash: blue
equity: yellow
fixed income: red

我还注意到我在 DataFrame 的 sort_asset 列中添加了可用于对资产进行正确排序的列,并且我正在使用它来确保对堆栈进行正确排序。

我确定我错过了一些简单的东西,因为我是 altair 的新手。我可以在上面的代码中更改什么以呈现正确的颜色和顺序?

标签: altair

解决方案


这是 Altair 版本 2 中的一个已知错误:复合图表中不保留排序字段。一些细节(包括解决方法的想法)在这里:https ://github.com/altair-viz/altair/issues/820

Altair 3.0 修复了这个错误,应该会在下周的某个时间发布。


推荐阅读