如何使用Altair按日期时间值突出显示栏 [英] How to highlight a bar by datetime value with Altair

查看:159
本文介绍了如何使用Altair按日期时间值突出显示栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于:



请注意,在此处使用完整的ISO时间字符串非常重要,因为Javascript所用的时区在解析日期的更改取决于日期的格式(例如,在大多数浏览器中, 2019-03-0 1 被解析为UTC时间,而 2019-03-01T00:00:00 被解析为本地时间)标准日期格式因浏览器而异。



有关Java语言日期解析的更多信息,请参阅 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript / Reference / Global_Objects / Date / parse


Similar to : https://altair-viz.github.io/gallery/bar_chart_with_highlighted_bar.html, is it possible to highlight a bar based on a specific date time value? I can't quite seem to make it work.

import pandas as pd
import altair as alt
import datetime

df = pd.DataFrame(
    {
        "year": [2019, 2019, 2019],
        "month": [1, 3, 7],
        "day": [1, 1, 1],
        "value": [5, 7, 9],
    }
)


df["Mth"] = pd.to_datetime(dict(year=df["year"], month=df["month"], day=df["day"]))
df.drop(
    ["year", "month", "day"], axis=1, inplace=True
)  # columns not present in my actual data set


alt.Chart(df).mark_bar(size=30).encode(
    x="Mth",
    y="value",
    color=alt.condition(
        alt.datum.Mth == "2019-03-01", alt.value("orange"), alt.value("steelblue")
    ),
    tooltip=[alt.Tooltip("value", title="value"), alt.Tooltip("Mth", title="Month"),],
)

screen shot of output

解决方案

Your expression is not working because you are comparing a temporal value to a string. You need to parse the date string before doing the comparison, which you can do using the Vega Expression functionality:

alt.Chart(df).mark_bar(size=30).encode(
    x="Mth",
    y="value",
    color=alt.condition(
        alt.datum.Mth == alt.expr.toDate('2019-03-01T00:00:00'),
        alt.value("orange"), alt.value("steelblue")
    ),
    tooltip=[alt.Tooltip("value", title="value"), alt.Tooltip("Mth", title="Month"),],
)

Note that it's important to use the full ISO time string here, because the timezone used by Javascript when parsing dates changes depending on how the date is formatted (e.g. in most browsers, "2019-03-01" is parsed as UTC time, while "2019-03-01T00:00:00" is parsed as local time) and parsing of non-standard date formats varies from browser to browser.

For more than you'd ever want to know about Javascript date parsing, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse.

这篇关于如何使用Altair按日期时间值突出显示栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆