首页 > 解决方案 > 笨手笨脚地在同一张图表上绘制两组季节性数据

问题描述

自 2017 年以来,我有一系列月度库存数据。自 2018 年 12 月以来,我有一系列库存预测

我正在尝试按季度绘制库存数据,然后覆盖 2019 年 1 月到 2019 年 12 月的库存预测。

数据框如下所示:

在此处输入图像描述

我尝试制作图表的第一种方法确实显示了我想要的所有数据,但我无法控制inventory_zj线条的颜色。它的颜色似乎以color=year(date):Nalt.Chart配置的为主。它忽略了color='green'I 传递给mark_line()

base = alt.Chart(inv.loc['2000':].reset_index(), title=f"usa total inventory").mark_line().encode(
    x='month',
    y="inventory",
    color="year(date):N"
)

#this ignores my 'green' color instruction, and marks it the same light blue 2019 color
joe = base.mark_line(color='green').encode(
    alt.Y('inventory_zj', scale=alt.Scale(zero=False), )
)

base+joe

在此处输入图像描述

我尝试使用分层系统,但它根本不起作用——我无法让它显示“joe”层

base = alt.Chart(inv.loc['2000':].reset_index(), title=f"usa total inventory").encode(
    x='month(date)'
)

doe = base.mark_line().encode(
    alt.Y('inventory', scale=alt.Scale(zero=False), ),
    color="year(date):N"
)


joe = base.mark_line(color="green").encode(
    alt.Y('inventory_zj', scale=alt.Scale(zero=False), ),
)



#looks identical to the first example
alt.layer(
    doe, joe
).resolve_scale(
    y='shared'
).configure_axisLeft(labelColor='black').configure_axisRight(labelColor='green',titleColor='green')

#independent shows a second y-axis (which is different from the left y-axis) but no line
alt.layer(
    doe, joe
).resolve_scale(
    y='independent'
).configure_axisLeft(labelColor='black').configure_axisRight(labelColor='green',titleColor='green')

在此处输入图像描述

我觉得我一定是试图以一种根本错误的方式组装这张图表。我应该能够共享相同的左 y 轴,将历史数据按年份着色,并为 2019 年的预测数据提供独特的颜色。但我似乎把它弄得一团糟。

标签: altair

解决方案


自定义可视化文档中所述,有多种方法可以指定线条颜色等具有明确定义的层次结构:编码覆盖标记属性,它覆盖顶级配置。

在您的图表中,您编写base.mark_point(color='green'),其中base包含覆盖标记属性的颜色编码。如果您没有从 base 派生图层(因此它没有颜色编码),那么该线将如您所愿为绿色。像这样的东西:

base = alt.Chart(inv.loc['2000':].reset_index(), title=f"usa total inventory")

inventory = base.mark_line().encode(
    x='month',
    y="inventory",
    color="year(date):N"
)

joe = base.mark_line(color='green').encode(
    x='month',
    y=alt.Y('inventory_zj', scale=alt.Scale(zero=False))
)

inventory + joe

推荐阅读