python - Altair:如何向包含行的条形图添加标签

标签 python python-3.x jupyter-notebook altair

当尝试向包含行的 Altair 条形图添加标签时,我收到 SchemaValidationError。我正在谈论像这样的标签: https://altair-viz.github.io/gallery/bar_chart_with_labels.html

我说的是带有行的条形图或“水平分组条形图”,如下所示: https://altair-viz.github.io/gallery/grouped_bar_chart_horizontal.html

这是不起作用的代码:

from vega_datasets import data

source = data.barley()

bars = alt.Chart(source).mark_bar().encode(
    x='sum(yield):Q',
    y='year:O',
    row='variety:N',
)
bars

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='sum(yield):Q'
)

bars + text

如果我删除条形图中的行选项,它会按预期工作:

bars = alt.Chart(source).mark_bar().encode(
    x='sum(yield):Q',
    y='year:O'
)
bars

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='sum(yield):Q'
)

bars + text

将行添加到“mark_text”方法也没有帮助...

最后,我希望看到条形右侧的标签,如下所示: https://imgur.com/KFJtNkb

最佳答案

您的代码片段的错误是

ValueError: Faceted charts cannot be layered.

一般来说,不能保证两个分面图表具有能够分层的匹配分面,因此 Vega-Lite 不允许分面图表分层。

解决这个问题的方法是对分层图表进行分面,而不是对分面图表进行分层。例如:

import altair as alt
from vega_datasets import data

source = data.barley()

bars = alt.Chart(source).mark_bar().encode(
    x='sum(yield):Q',
    y='year:O',
)
bars

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='sum(yield):Q'
)

(bars + text).facet(row='variety:N')

enter image description here

关于python - Altair:如何向包含行的条形图添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148240/

相关文章:

python-3.x - 为什么将字节传递给类 str 构造函数很特别?

javascript - 元素未完全全屏显示

github - 如何在 github 上显示 .ipynb 文件?

python - 如何使用FastAPI将视频帧和文本返回到HTML页面?

python - 当我使用线程时无法使用 xlsxwriter 进行写入

python - 以非常高的质量在 Python 中保存图像

python - Pandas DataFrame 括号访问器 [ ] 更喜欢列还是行?

python - 使用 Pandas 解析一列中的 CSV 数据

python - 仅打印字符串中的元音字母

python - 如何过滤 DataFrame 列表中的数字(n>3)?