python - 当 x 轴包含重复项时,altair/vega-lite 中的 mark_line 会对数据重新排序

标签 python vega-lite altair

我注意到,当 x 轴上存在重复且 y 轴上的值不同时,不会考虑提供数据的顺序。最大值与前一个点相关联,最小值与下一个点相关联。例如,在创建 CDF(累积分布函数)时,这不是我所期望的。

我尝试提供带有索引的EncodingSortField,但这不起作用。我可以通过删除数据中具有最小值的行来绘制我想要的图表,但随后我需要手动添加点。

这是设计使然吗?或者我错过了什么?

下面是一个可重现的示例。

import pandas as pd
import altair as alt

df = pd.DataFrame({'x':[-1, 0, 0, 1, 2],
                   'y':[-1, 0, 1, 2, 3],
                   'index':[0, 1, 2, 3, 4]})

step = alt.Chart(df).mark_line(interpolate="step", point=True).encode(
    x='x:Q', 
    y='y:Q',
).properties(width=150, 
             height=150, 
             title="interpolate='step'")

step_after = step.mark_line(
    interpolate='step-after', 
    point=True
).properties(title="interpolate=step-after")

step_before = step.mark_line(
    interpolate='step-before', 
    point=True
).properties(title="interpolate=step-before")

sort = step.encode(
    y=alt.Y('y:Q', 
            sort=alt.EncodingSortField(field='index', 
                                       op='sum'))
).properties(title='sort by index')

expected = (step_before.properties(data=df[df.index != 1], 
                                   title='expected') + 
            alt.Chart(pd.DataFrame([{'x':0, 
                                     'y':0}])
                     ).mark_circle().encode(
                x='x:Q', y='y:Q')
           )

(step | step_before | step_after) & (sort | expected)

altair-charts reprexpy package于2018年11月15日创建

import reprexpy
print(reprexpy.SessionInfo())
#> Session info --------------------------------------------------------------------
#> Platform: Darwin-18.2.0-x86_64-i386-64bit (64-bit)
#> Python: 3.6
#> Date: 2018-11-15
#> Packages ------------------------------------------------------------------------
#> altair==2.2.2
#> pandas==0.23.4
#> reprexpy==0.2.1

谢谢。

最佳答案

传递到 Altair 的数据行的顺序不会保留在图表输出中,这是设计使然。

如果您希望数据条目以特定顺序绘制,您可以使用 order 编码来明确指定;文档中的示例如下:https://altair-viz.github.io/gallery/connected_scatterplot.html

就您而言,如果您将 order="index:Q" 传递到您的编码列表,我相信结果将是您所期望的。

关于python - 当 x 轴包含重复项时,altair/vega-lite 中的 mark_line 会对数据重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53323239/

相关文章:

powerbi - 在 Vega-Lite (Deneb) 中设置动态域

tooltip - 格式化 Altair 等值线图图例比例和工具提示

python - 如何修改我的代码以提供 dict 数据类型的输入?

python - 返回列表中最常出现的单词

Python 删除包含大量缺失值的列

python - 如何使用 Python 从 HTML 文档中提取信息?

Vega-Lite - 处理大量数据的最佳方式是什么?

python - 如何对图中每一行的 Y 轴标签进行不同的排序?

python - 如何使用 Python Altair 将 x 轴和 y 轴的交点从 0 移动到 1?

python - 如何使用 Altair 在散点图中突出显示标记?