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
相关产品推荐
相关产品推荐

