【问题标题】:Altair bar chart assign specific colors based on dataframe columnAltair 条形图根据数据框列分配特定颜色
【发布时间】:2020-06-25 16:17:49
【问题描述】:

我正在使用 Altair 在 Jupyter 笔记本中制作甘特图,如 here 所述。

如何为每个任务分配特定的条形颜色?感谢您的帮助。

已安装 Pandas、altair 和 vega。使用 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

【问题讨论】:

标签: jupyter-notebook altair


【解决方案1】:

添加

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

成功了

【讨论】:

  • 谢谢! :N 是什么意思?我在文档中看到了它的版本(:O:Q 等),但我不知何故错过了它的含义。
  • 好问题! :N 是编码数据类型的简写,在本例中为 Nominal。一般来说,将它们包括在内是一种很好的做法。欲了解更多信息,请参阅altair-viz.github.io/user_guide/…
猜你喜欢
  • 1970-01-01
  • 2015-07-29
  • 2021-01-18
  • 2017-04-01
  • 2020-11-01
  • 2020-09-05
  • 2022-01-10
  • 2020-09-18
  • 2019-12-18
相关资源
最近更新 更多