向数据点添加 X-Y 偏移量

Adding X-Y offsets to data points

我正在寻找一种方法来为绘制的数据点指定 X-Y​​ 偏移量。我刚接触 Altair,所以请多多包涵。

情况:我有一个记录 30 人每日测量值的数据集。每个人每天都可以记录几种不同类型的测量值。

示例数据集和绘图,有 2 个人和 2 种测量类型:

import pandas as pd

df = pd.DataFrame.from_dict({"date": pd.to_datetime(pd.date_range("2019-12-01", periods=5).repeat(4)), 
        "person": pd.np.tile(["Bob", "Amy"], 10), 
        "measurement_type": pd.np.tile(["score_a", "score_a", "score_b", "score_b"], 5), 
        "value": 20.0*np.random.random(size=20)})

import altair as alt

alt.Chart(df, width=600, height=100) \
            .mark_circle(size=150) \
            .encode(x = "date",
                    y = "person",
                    color = alt.Color("value"))

这给了我这张图:

在上面的示例中,2 种测量类型绘制在彼此之上。我想根据 "measurement_type" 列向圆圈添加偏移量,以便它们都可以在图中的日期-人物位置周围可见。

这是我想要实现的模型:

我一直在搜索文档,但还没有想出如何做到这一点 - 一直在试验 "stack" 选项,以及 dxdy 选项,。 .. 我觉得这应该只是另一个编码通道(offset 或类似),但它不存在。

任何人都可以指出正确的方向吗?

好吧,我不知道你会得到什么结果,直到知道,但也许写一个带有参数的函数,比如def chart(DotsOnXAxis, FirstDotsOnYAxis, SecondDotsOnYAxis, OffsetAmount) 然后将这些变量放在正确的位置。

如果你想用点进行偏移,可以将其放入如下系统:SecondDotsOnYAxis = FirstDotsOnYAxis + OffsetAmount

目前 Altair 中没有偏移编码的概念,因此最好的方法是将列编码与 y 编码结合起来,类似于 Altair 文档中的 Grouped Bar Chart 示例:

alt.Chart(df,
    width=600, height=100
).mark_circle(
    size=150
).encode(
    x = "date",
    row='person',
    y = "measurement_type",
    color = alt.Color("value")
)

然后您可以使用标准 chart configuration 设置微调结果的外观:

alt.Chart(df,
    width=600, height=alt.Step(25)
).mark_circle(
    size=150
).encode(
    x = "date",
    row='person',
    y = alt.Y("measurement_type", title=None),
    color = alt.Color("value")
).configure_facet(
    spacing=10
).configure_view(
    strokeOpacity=0
)