Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altair bar chart assign specific colors based on dataframe column

I am making a Gantt chart in Jupyter notebook using Altair, as described here.

How can I assign specific bar colors to each task? Thanks for any help.

Pandas, altair, and vega are installed. Using Windows 10, Python 3.7.6, Conda 4.6.14.

mytaskbars = pd.DataFrame([
    {"task": "Task1a", "start": '2020-06-01', "end": '2020-09-30', "color": 'royalblue'},
    {"task": "Task1b", "start": '2020-06-01', "end": '2021-03-31', "color": 'deepskyblue'},
    {"task": "Task1c", "start": '2020-09-30', "end": '2021-03-31', "color": 'dodgerblue'},
    {"task": "Task2", "start": '2020-06-01', "end": '2021-03-31', "color": 'red'},
    {"task": "Task3", "start": '2020-06-01', "end": '2021-08-02', "color": 'orange'},
    {"task": "Task4", "start": '2020-10-01', "end": '2021-03-31', "color": 'green'},
])

mytaskbars["start"] = pd.to_datetime(mytaskbars["start"])
mytaskbars["end"] = pd.to_datetime(mytaskbars["end"])


chart = alt.Chart(mytaskbars).mark_bar(opacity=0.7).encode(
    x=alt.X('start', axis=alt.Axis(title='Date', labelAngle=-45, format = ("%b %Y"))),
    x2 = 'end',
    y=alt.Y('task', axis=alt.Axis(title=None)),
    color = 'color'
)

chart

enter image description here

like image 307
a11 Avatar asked Dec 02 '25 04:12

a11


1 Answers

Adding

    color=alt.Color('color:N', scale = None)

does the trick

enter image description here

like image 80
eitanlees Avatar answered Dec 06 '25 22:12

eitanlees



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!