基于分组统计,对Altair图表的分类因素进行排序

4

我希望根据某些组的统计数据,如平均值、标准差等,更改Altair图表的分面顺序。

在某些情况下,排序函数可能更复杂,例如两个移动平均数之间的差值、EWMA的斜率等,因此如果可能的话,我也想能够“传递”顺序。

这是可测试的代码:

import pandas as pd
import numpy as np
import altair as alt

alt.renderers.enable('notebook')

# make some data to test
N = 500
df = pd.DataFrame({
    'Date Time': pd.date_range('2019-06-19', periods=N, freq='H'),
    'A':  np.random.normal(6, 1, N),
    'B': np.random.normal(5, 1, N),
    'C': np.random.normal(7, 1, N),
    'D': np.random.normal(8, 1, N)
}).melt('Date Time')

# render the chart using facets
p = alt.Chart(df).mark_point().encode(
    facet='variable',
    y='value',
    x='Date Time',
    color='variable',
)

# set some aditional properties
p.properties(width=230, height=150, columns=3).resolve_scale()

以下代码会生成这样一个图表,其中各个方块按字母顺序排序:

enter image description here

我希望排序方式是按平均值从大到小排序:

var_order = df.groupby('variable').mean().sort_values('variable', ascending=False).index.values
var_order

产生:

array(['D', 'C', 'B', 'A'], dtype=object)

我看到一些帖子表明在x和y上排序是可能的,但这种情况是我想要对面进行排序。

1个回答

4
您可以在facet编码中使用EncodingSortField,例如:
p = alt.Chart(df).mark_point().encode(
    y='value',
    x='Date Time',
    color='variable',
    facet=alt.Facet('variable',
        sort=alt.EncodingSortField('value', op='mean', order='descending')
    )
)

# set some aditional properties
p.properties(width=230, height=150, columns=3).resolve_scale()

若要进行更为复杂的计算,可使用计算转换和/或聚合转换来计算新字段,然后按该字段排序。

图表输出


4
好的,很快就完成了 :). 我发布帖子后,去咖啡馆吃午餐,然后你已经发布了答案。顺便提一下,Altair 的整体工作非常出色。到目前为止,它是我发现的最接近 R Grid/Lattice 的工具,并且与 Bokeh 相比,具有更直观、易于使用的界面(在我看来)。继续保持出色的工作......如果有机会,也许我会在 Stack Overflow 上回答一个与 Altair 相关的问题。 - Randall Goodwin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接