pythonmatplotlibaltair

Color areas in an altair plot


I want to create colored areas in a plot to essentially mark a "region". In matplotlib I could achieve this by manipulating barh:

import polars as pl
import matplotlib.pyplot as plt

aux = pl.DataFrame([
    {"id": 1, "start": 1, "end": 15},
    {"id": 3, "start": 16, "end": 94},
    {"id": 4, "start": 95, "end": 100},
])

plt.barh(y=aux["id"], width=aux["end"]-aux["start"], left=aux["start"])

a plot with three horizontal bars at heights corresponding to "id" and spanning the areas delimited by the "start" and "end" columns

How can I reproduce this plot in altair?

I tried making horizontal bar plots, where I got the 3 bars all starting at 0 rather than start. I attempted to do it with the XOffset parameter, but the parameter seemed to cause no change (though it didn't raise any error). I tried to use the mark_rect encoding but for whatever reason I can't make it create three rectangles (it creates one large one).


Solution

  • You can set the start of each bar via the x encoding and the end of the bar via the x2 encoding. There is an example in the gallery with more details.