Altair: bar chart pointing downwards from offset

437 views Asked by At

I am trying to reproduce the following visualization using altair:

enter image description here

The tricky part is the bars pointing downwards from 100. In the old days I would use matplotlib and subtract 100 from the data but keep the old label ticks. Altair is, fortunately, very true to the data, so this trick doesn't seem to work.

Is there a way to offset the "origin" of the bars? Or is there any other trick that could give the desired result?

Here is a minimal sample code that is relevant:

import altair as alt
import pandas as pd

data = pd.DataFrame({
    'num': [0, 1],
    'value': [80, 120],
})

alt.Chart(data).mark_bar().encode(x='num', y='value')
1

There are 1 answers

1
jakevdp On BEST ANSWER

You can do this by using a y2 encoding to specify the baseline. Adapting your example:

alt.Chart(data).transform_calculate(
  baseline='100'
).mark_bar(
  orient='vertical'
).encode(
  x='num', y='value', y2='baseline:Q'
)

enter image description here