Search code examples
pythonaltair

How to draw bar charts with labels


I'm trying to execute the code from official documentation (Bar Chart with Labels) and use exactly the same lines:

import altair as alt
from vega_datasets import data


source = data.wheat()

base = alt.Chart(source).encode(
    x='wheat',
    y="year:O",
    text='wheat'
)
base.mark_bar() + base.mark_text(align='left', dx=2)

but when I add

base.save('/path/to/chart.png')

to save chart as PNG file I get

altair.utils.schemapi.SchemaValidationError: '{'data': {'name': 'data-76d1ce26ea5761007c35827e1564d86c'}, 'encoding': {'text': {'field': 'wheat', 'type': 'quantitative'}, 'x': {'field': 'wheat', 'type': 'quantitative'}, 'y': {'field': 'year', 'type': 'ordinal'}}}' is an invalid value.

'mark' is a required property

Is it a bug or I'm doing something wrong?


Solution

  • This is not related to saving the chart, you would see the same issue if you tried to display base by itself. Altair charts need to have marks and this check is performed when the chart is rendered for display or saved to a file. In your example, the marks are added when you layer the bar and text mark and this layered chart (with marks) is what is displayed. If you want to save this layered chart (rather than the base chart) you could do it without issues:

    chart = base.mark_bar() + base.mark_text(align='left', dx=2)
    chart.save('chart.png')