【问题标题】:Layered or Facet bar plot with label values in AltairAltair 中带有标签值的分层或 Facet 条形图
【发布时间】:2018-06-03 02:38:29
【问题描述】:

我正在尝试创建一个简单的条形图(特定字段有多个列):

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
) 

现在,这个图效果很好,但是当我尝试在条形顶部添加值标签时 like this:

text = bars.mark_text(
    align='center',
).encode(
    text='acc:Q'
)

bars + text

它会抛出以下错误:

ValueError: Objects with "config" attribute cannot be used within LayerChart. Consider defining the config attribute in the LayerChart object instead.

如何将条形标签添加到分面/分层图的条形图中的每个条形?

【问题讨论】:

  • 如果您删除 .configure_view.configure_axis 调用,它会有所帮助。我没有你的数据框,但是当我在没有column(堆叠条)的情况下尝试它时,文本确实呈现了。

标签: python plot altair


【解决方案1】:

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
)

【讨论】:

  • 根据您在git-issue#920 中的代码,列规范column='task_name:N' 应该从bars 移出到alt.layer() 内部
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
相关资源
最近更新 更多