我希望每个子图根据定义条形大小的值对标签进行排序。
查看示例图片:
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'
)
关于python - 如何对图中每一行的 Y 轴标签进行不同的排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901556/