【问题标题】:Adding X-Y offsets to data points向数据点添加 X-Y 偏移
【发布时间】:2019-12-24 10:16:58
【问题描述】:

我正在寻找一种方法来指定绘制数据点的 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"))

这给了我这个图表:

在上面的示例中,两种测量类型相互叠加。我想根据“measurement_type”列为圆圈添加一个偏移量,以便它们都可以在图表中的日期人位置周围可见。

这是我想要实现的目标的模型:

我一直在搜索文档,但还没有弄清楚如何做到这一点 - 一直在尝试使用“堆栈”选项,dxdy 选项,... 我觉得这应该只是另一个编码通道(offset 或类似的),但它不存在。

谁能指出我正确的方向?

【问题讨论】:

    标签: python altair


    【解决方案1】:

    目前 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
    )
    

    【讨论】:

    • 好的,这看起来确实是最好的解决方案。偏移编码会包含在路线图中吗?
    【解决方案2】:

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

    如果你想要一个点的偏移量,可以放在一个系统中,比如:SecondDotsOnYAxis = FirstDotsOnYAxis + OffsetAmount

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多