问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/60331614/how-to-highlight-a-bar-by-datetime-value-with-altair