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

Bar*_*art 5 python vega-lite altair

我希望每个子图根据定义条形大小的值对标签进行排序。

请参阅示例图像:

在此处输入图片说明

data = {'label': ['A','A','B','B'], 'variable': ['x', 'y', 'x', 'y'], 'value':[2,4,3,1]}
    df = pd.DataFrame.from_dict(data)
    selector = alt.selection_single(empty='all', fields=['label'])
    bar = alt.Chart(df,title='My Plot').mark_bar().encode(
        alt.Y('label', sort=alt.EncodingSortField(field="value", op="mean", order='ascending'), axis=alt.Axis(title='Label')),
        alt.X('value:Q', axis=alt.Axis(format='%', title='Value')),
        alt.Row('variable', title='Variable'),
        color=alt.condition(selector, alt.value('orange'), alt.value('lightgray')),
        tooltip=[alt.Tooltip('label', title='Label'),
                 alt.Tooltip('value:Q', format='.2%', title='Value'),]
    ).add_selection(selector)
    chart = (bar).properties(width=700, height=300)
    display(chart)
Run Code Online (Sandbox Code Playgroud)

在示例中,标签 (A, B) 现在根据这些标签的所有值的平均值进行排序。我希望标签 X 的顺序为 BA,标签 Y 的顺序为 AB(因此根据 Altair 图行中显示的标签值降序)。

jak*_*vdp 2

通过设计,分面图共享它们的轴,因此这意味着当您对列进行排序时,您将按整个数据集对两个轴进行排序。

如果您希望每个图表的轴单独排序,我相信唯一的方法是手动过滤数据集并连接图表。这是您可以执行此操作的一种方法:

import altair as alt
import pandas as pd

df = pd.DataFrame({'label': ['A','A','B','B'],
                   'variable': ['x', 'y', 'x', 'y'],
                   'value':[2,4,3,1]})

base = alt.Chart(df).mark_bar().encode(
  alt.Y('label', axis=alt.Axis(title='Label'), 
        sort=alt.EncodingSortField(field="value", op="sum", order='descending')),
  alt.X('value:Q', axis=alt.Axis(format='d', title='Value')),
  tooltip=[alt.Tooltip('label', title='Label'),
           alt.Tooltip('value:Q', format='d', title='Value'),],
)

alt.vconcat(
  base.transform_filter("datum.variable == 'x'").properties(title='x'),
  base.transform_filter("datum.variable == 'y'").properties(title='y'),
  title='My Chart'
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述