Reputation: 23
I have a pandas dataset with three columns ('Time', 'Actual Value' , 'Prediction'). I am trying to plot two lines in same figure using Altair package in python:
-Actual Value vs Time
-Prediction vs Time
In parts of the dataset, I have null values (np.nan) in 'Actual Price' and 'Prediction' columns.
When I add tooltips, I get 'null' as text in parts that I have np.nan:
Time : August 30, 2018
Actual Value : null
Prediction : 150
I want to change the text in the tooltip to a customize one (like: 'Not Available').
Desired output in tooltip :
Time : August 30, 2018
Actual Value : Not Available
Prediction : 150
data = {'Time': pd.date_range(start='1/1/2018', periods=8, freq='M'),
'Actual Value': [100, 150, 200, 120, 180, 150, 110, np.NaN],
'Prediction' : [np.NaN, 140, 180, 110, 160, 140, 120, 150]}
df = pd.DataFrame (data)
## Altair Plots
base = alt.Chart(df).transform_calculate(
line1="'Actual Value'",
line2="'Prediction'",
).properties(
height=360,
width = 800
)
scale = alt.Scale(domain=["Actual Value", "Prediction"], range=['blue', 'orange'])
line1 = base.mark_line(opacity=0.8,color='blue').encode(
x=alt.X('Time:T',title='Time'),
y=alt.Y('Actual Value:Q',axis = alt.Axis(title="Price")),
color = alt.Color('line1:N', scale=scale, title=' '),
)
line2 = base.mark_line(color='orange').encode(
x=alt.X('Time:T',title='Time'),
y=alt.Y('Prediction:Q',axis = alt.Axis(title="Price")),
color = alt.Color('line2:N',scale=scale, title=' '),
)
# Tooltip Function
def createTooltip():
"""
This function creates a tooltip containing the date, and prices displayed upon hover
"""
hover = alt.selection_single(
fields=["Time"],
nearest=True,
on="mouseover",
empty="none",
clear="mouseout",
)
tooltips = alt.Chart(df).mark_rule(strokeWidth=0.5, color="black", strokeDash=[4,2]).encode(
x='Time',
opacity=alt.condition(hover, alt.value(1), alt.value(0)),
tooltip=["Time",
alt.Tooltip("Actual Value:N", title='Actual Value'),
alt.Tooltip("Prediction:N", title='Prediction')]
).add_selection(hover)
return tooltips
tooltips = createTooltip()
alt.layer(line1+line2, tooltips).interactive()
Upvotes: 2
Views: 814
Reputation: 86320
You can do this using a calculate transform. For example:
tooltips = alt.Chart(df).transform_calculate(
P="isValid(datum.Prediction) ? datum.Prediction : 'Undefined'",
A="isValid(datum['Actual Value']) ? datum['Actual Value'] : 'Undefined'"
).mark_rule(strokeWidth=0.5, color="black", strokeDash=[4,2]).encode(
x='Time',
opacity=alt.condition(hover, alt.value(1), alt.value(0)),
tooltip=["Time",
alt.Tooltip("A:N", title='Actual Value'),
alt.Tooltip("P:N", title='Prediction')]
).add_selection(hover)
Upvotes: 4