如何更改 Altair boxplot 信息框以显示均值而不是中位数?

How to change Altair boxplot infobox to display mean rather than median?

我在 Python 中使用 Altair 库创建了一些数据的可视化。目前悬停信息框显示中位数。如何更改聚合以显示平均值?

如果您谈论的是 https://altair-viz.github.io/gallery/boxplot.html, there is no easy way to change the median to the mean. This is because the median is hard-coded in the vega-lite boxplot macro on which this is based: https://vega.github.io/vega-lite/docs/boxplot.html

示例中的标准箱线图

如果您想要更大的灵活性,可以手动构建图表组件并使用均值而不是中位数;例如:

import altair as alt
from vega_datasets import data

source = data.population.url

alt.LayerChart(data=source).transform_aggregate(
    min="min(people)",
    max="max(people)",
    mean="mean(people)",
    q1="q1(people)",
    q3="q3(people)",
    groupby=["age"]
).encode(
    x='age:O',
    tooltip=['min:Q', 'q1:Q', 'mean:Q', 'q3:Q', 'max:Q']
).add_layers(
    alt.Chart().mark_rule().encode(y='min:Q', y2='max:Q'),
    alt.Chart().mark_bar(width=15).encode(y='q1:Q', y2='q3:Q'),
    alt.Chart().mark_tick(color='white', width=15).encode(y='mean:Q'),
)