Tar*_*ula 2 python plot altair
我正在尝试创建一个简单的条形图(特定字段有多个列):
bars = alt.Chart(df_probing).mark_bar(stroke='transparent').encode(
alt.X('model_name:N', scale=alt.Scale(rangeStep=12), axis=alt.Axis(title='')),
alt.Y('acc:Q', axis=alt.Axis(title='Accuracy', grid=False)),
color=alt.Color('model_name:N'),
column='task_name:N'
).configure_view(
stroke='transparent'
).configure_axis(
domainWidth=0.8
)
Run Code Online (Sandbox Code Playgroud)
现在,该图运行良好,但是当我尝试在条形顶部添加值标签时,如下所示:
text = bars.mark_text(
align='center',
).encode(
text='acc:Q'
)
bars + text
Run Code Online (Sandbox Code Playgroud)
它引发以下错误:
ValueError: Objects with "config" attribute cannot be used within LayerChart. Consider defining the config attribute in the LayerChart object instead.
Run Code Online (Sandbox Code Playgroud)
如何将条形标签添加到分面/分层图上条形图中的每个条形?
该configure_*方法仅适用于顶级图表;错误试图告诉你这一点,但它并不像它可能的那样清楚。
解决方法是将配置移到顶层对象;也就是说,做这样的事情:
bars = alt.Chart(df_probing).mark_bar(stroke='transparent').encode(
alt.X('model_name:N', title='', scale=alt.Scale(rangeStep=12)),
alt.Y('acc:Q', title='Accuracy', axis=alt.Axis(grid=False)),
color='model_name:N',
column='task_name:N'
)
text = bars.mark_text(
align='center',
).encode(
text='acc:Q'
)
alt.layer(bars, text).configure_view(
stroke='transparent'
).configure_axis(
domainWidth=0.8
)
Run Code Online (Sandbox Code Playgroud)