Altair实现非堆叠分组柱状图+独立双轴折线图
问题
现有一张Altair图表,需要将其中的堆叠柱状图改为类似Seaborn示例sns.barplot(data=df, x="island", y="body_mass_g", hue="sex")的分组并列柱状图,同时保留带独立Y轴的折线图。尝试将周设为X轴列时出现分面相关错误,无法实现独立轴效果(注:柱状图与折线图Y轴不同)。现有代码如下:
# create line chart line = ( alt.Chart( df_line, title= chart_title) .mark_line(interpolate="basis") .encode( x=alt.X("yearmonthdate(WEEK):T", title='Week'), y=alt.Y("PCT_LINE:Q", axis=alt.Axis(format='%'), title = 'Line'), tooltip=["yearmonthdate(WEEK):O", "value:Q"] ) .properties(width=500, height=300) ) # create bar chart bar = ( alt.Chart( df_bars) .mark_bar(interpolate="basis") .encode( x=alt.X("yearmonthdate(week):T", title='Week'), y=alt.Y("value:Q", axis=alt.Axis(format='%'), title = y_axis_legend), #, stack=False color=alt.Color("variable:N", title= 'Legend'), tooltip=["yearmonthdate(WEEK):O", "variable:N", "value:Q"] ) .properties(width=500,height=300) ) bar plot = (line + bar).resolve_scale(y="independent") plot
解决方案
要实现分组并列柱状图+独立Y轴折线图,核心是给柱状图的X轴添加分组偏移,同时保证折线图与柱状图的X轴对齐,具体修改如下:
修改后完整代码
# 创建折线图 line = ( alt.Chart(df_line, title=chart_title) .mark_line(interpolate="basis") .encode( x=alt.X("yearmonthdate(WEEK):T", title='Week', axis=alt.Axis(labelAngle=-45)), y=alt.Y("PCT_LINE:Q", axis=alt.Axis(format='%'), title='Line'), tooltip=["yearmonthdate(WEEK):O", "PCT_LINE:Q"] ) .properties(width=500, height=300) ) # 创建分组并列柱状图 bar = ( alt.Chart(df_bars) .mark_bar(width=15) # 设置柱子宽度,避免并列时重叠 .encode( x=alt.X("yearmonthdate(week):T", title='Week'), xOffset=alt.XOffset("variable:N"), # 按分组变量横向偏移,实现并列效果 y=alt.Y("value:Q", axis=alt.Axis(format='%'), title=y_axis_legend), color=alt.Color("variable:N", title='Legend'), tooltip=["yearmonthdate(WEEK):O", "variable:N", "value:Q"] ) .properties(width=500, height=300) ) # 合并图表并保留独立Y轴 plot = (line + bar).resolve_scale(y="independent") plot
关键说明
xOffset是实现分组并列的核心:它会让同一时间点下不同variable的柱子横向偏移,形成Seaborn式的并列效果。- 调整
mark_bar(width):根据数据量和图表宽度设置合适的柱子宽度,避免并列柱子重叠或间距过大。 - 统一X轴格式:折线图和柱状图的X轴使用相同的时间编码,确保两者刻度完全对齐。
内容的提问来源于stack exchange,提问作者AIFOS
相关产品推荐
相关产品推荐

