我有一个包含三列的 pandas 数据集(“时间”、“实际值”、“预测”)。 我正在尝试使用 python 中的 Altair 包在同一个图中绘制两条线:
-Actual Value vs Time
-Prediction vs Time
在部分数据集中,“实际价格”和“预测”列中有空值 (np.nan)。
当我添加工具提示时,我在 np.nan 的部分中得到“null”文本:
Time : August 30, 2018
Actual Value : null
Prediction : 150
我想将工具提示中的文本更改为自定义文本(例如:“不可用”)。
工具提示中所需的输出:
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()
最佳答案
您可以使用 calculate transform 来执行此操作。例如:
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)
关于python - 处理 python Altair 工具提示文本中的 "null"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67427923/