dexter04
dexter04

Reputation: 123

Creating stacked chart in Altair with multiple axes and gaps

I am trying to create a chart depicting two different processes on the same timescale in Altair. Here is an example in excel

Here is an example

I have generated the stacked horizontal bar chart below in excel using the following data. The numbers in red are offsets/gaps, not to be displayed in the final plot. Nothing special about these numbers, please feel free to use any other set of numbers.

enter image description here

The numbers in red are offsets and I would have posted an attempt, but I am completely out of my depth guessing what functionality to begin with. Any help would be greatly appreciated.

Upvotes: 0

Views: 223

Answers (1)

jakevdp
jakevdp

Reputation: 86443

Here's an example of how you might make a chart like this, using a conditional opacity to hide the offset values:

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'axis': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
    'value': [0.5, 0.9, 2, 1, 3, 1, 0.8, 1, 1.4, 1.1, 4.1, 0.3, 1.1],
    'label': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', None, 'C', None, 'F', 'G']
})

alt.Chart(df.reset_index()).mark_bar().encode(
    y=alt.Y('axis:O', scale=alt.Scale(domain=[2, 1])),
    x='value:Q',
    color=alt.Color('label:N', legend=None),
    opacity=alt.condition('isValid(datum.label)', alt.value(1), alt.value(0)),
    order=alt.Order('index:Q', sort='ascending')
)

enter image description here

Upvotes: 2

Related Questions