2

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

a11
  • 3,122
  • 4
  • 27
  • 66

1 Answers1

3

Adding

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

does the trick

enter image description here

eitanlees
  • 1,244
  • 10
  • 14
  • Thanks! what does the `:N` mean? I see versions of it in the documentation (`:O`, `:Q`, etc.) but I somehow missed what it means. – a11 Jun 25 '20 at 23:07
  • 1
    Good question! The `:N` is shorthand for the encoding data type, in this case Nominal. In general it's good practice to include them. For more information see https://altair-viz.github.io/user_guide/encoding.html#encoding-data-types – eitanlees Jun 26 '20 at 01:30