'Altair: formatting tooltip ordinal datetime
The output of my live tooltip example is:
Where the x-axis is formatted at ordinal dates; but the chart is also run through Streamlit, which appears to produce timestamps in milliseconds from the epoch. (Note: it appears Streamlit manipulates ordinal dates in some way. As such, I cannot reproduce an exact example, nor the exact tooltip output).
However, an example with millisecond code as the x-axis is as follows (I believe):
import altair as alt
import pandas as pd
import numpy as np
df = pd.DataFrame({
'x': range(20),
'y': pd.date_range(end='2022-01-18', periods=20, freq='B').view(np.int64) / int(1e6)
})
chart = alt.Chart(df).mark_rect().encode(
alt.X('x:O',
axis=alt.Axis(tickMinStep = 2, labelAngle=0),
),
alt.Y('y:Q', axis=alt.Axis(values=[0, 5, 10, 15, 20])),
alt.Color('y:Q'),
tooltip=alt.Tooltip('y:O', title='Date')
)
chart.save('ex.html')
Is there a way to format the y:O to print out %m %d, %Y datetime format?
Solution 1:[1]
If you were to first add a second y, say y2, to your dataframe that had the dates:
df = pd.DataFrame({
'x': range(20),
'y': pd.date_range(end='2022-01-18', periods=20, freq='B').view(np.int64) / int(1e6),
'y2': pd.date_range(end='2022-01-18', periods=20, freq='B')
})
You would just have to change your alt.Tooltip field and field type:
tooltip=alt.Tooltip('y2:T', title='Date')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MichiganMadeLearner |

