You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vega-Lite分组内滚动平均线无法显示问题求助

解决分组散点图中滚动平均线不显示的问题

你的问题出在窗口滚动平均未按分组字段单独计算,且数据排序未针对分组做处理,导致滚动平均线无法正确生成。以下是修正后的函数:

function log_scatter_and(df::DataFrame, other; smooth=2, title="Price by Number of Users")
    otherSym = Symbol(other)
    prices = price_and(df, other)
    # 先按分组字段、再按用户数排序,确保每个分组内数据有序
    sorted_df = sort(select(prices, [:Price, :Users, otherSym]), [otherSym, :Users])
    
    sorted_df |>
    @vlplot(width=640,height=512, title=title) +
    @vlplot(mark={:point, opacity=0.5}, color=otherSym, 
            x={field=:Users, scale={type="log"},title="Users"}, 
            y={:Price,title="Price per User"}) +
    @vlplot(transform=[
        # 按用户数+分组字段聚合均值
        { groupby=[:Users, otherSym], aggregate=[{ op=:mean, field=:Price, as="AvgPrice" }] },
        # 窗口计算时按分组字段分组,确保每个分组单独算滚动平均
        { groupby=[otherSym], frame=[-smooth,smooth], 
          window=[{ field="AvgPrice", op=:mean, as="rolling" }] }
        ],
        mark={:line,size=2,color=otherSym}, 
        x={:Users, title="Users"}, 
        y={"rolling:q", title="Average"})
end

关键修改点:

  • 排序逻辑调整:从仅按Users排序改为[otherSym, :Users]排序,保证每个分组内的用户数是有序的,滚动平均的窗口计算才有意义。
  • 窗口变换添加分组:在第二个transform的window操作中加入groupby=[otherSym],让滚动平均在每个分组内部独立计算,而不是全局计算。

修改后,每个分组(如不同年份)都会生成对应颜色的滚动平均线,和同组散点匹配显示。

内容的提问来源于stack exchange,提问作者leei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:26:12