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

标签 python vega-lite altair

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

查看示例图片:

enter image description here

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)

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

最佳答案

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

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

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'
)

enter image description here

关于python - 如何对图中每一行的 Y 轴标签进行不同的排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901556/

相关文章:

python - python 如何将 unicode 和非 unicode 元组视为平等的?

python - 查找 PySpark 中两个数据帧之间的更改

python - Altair 组合多个数据集

altair - 有没有一种方法可以缩放然后进行选择间隔而无需使用 Altair 进一步缩放

python - 将数据保存到磁盘与将数据存储在图中时,Altair 会更改图例的顺序

python - Altair Hconcat - 是否可以在同一 HConCat 中为图表配置不同的轴?

python - 如何在 Python 中使用 R 通过 Django 返回一个 R 图?

python - 由于 "perfect separation error",无法运行逻辑回归

vega - Vega/Lite 中的动画

python - 成对散点图矩阵