在下面代码生成的图表中,用户可以将鼠标悬停在线段上以在图表上显示一个点,并且该点的信息显示在图表上方。
import altair as alt
import numpy as np
import pandas as pd
df = pd.DataFrame({'x': np.linspace(0, 4, 1000)})
# df['y'] = np.sin(2 * np.pi * df['x'])
df['y'] = 1.9 * df['x']
select_point = alt.selection_single(fields=('x',), nearest=True, on='mouseover', empty='none')
line = alt.Chart(df).mark_line().encode(
x='x:Q',
y='y:Q',
)
points = line.mark_point(filled=True, size=100).encode(
opacity=alt.condition(select_point, alt.value(1.0), alt.value(0.0)),
).add_selection(select_point)
texts = alt.Chart(df, width=600, height=400).mark_text(
align='left', baseline='bottom', dx=+5, dy=-5, fontSize=12,
).encode(
x=alt.value(0.0),
y=alt.value(df['y'].max()),
text='_label:N',
opacity=alt.condition(select_point, alt.value(1.0), alt.value(0.0)),
).transform_calculate(
_label='"x = " + format(datum.x, ".2f") + ", y = " + format(datum.y, ".2f")',
)
alt.layer(line, points, texts)
有代码可以绘制正弦曲线和直线,尽管绘制正弦曲线的代码已被注释掉。当我运行脚本来显示正弦曲线时,我得到以下结果。
当我运行脚本来显示该行时,我得到以下内容。
我认为正弦曲线图上的标签文本恰到好处。但是,线条图上的标签文本距离图表顶部太近。有没有办法使标签文本始终偏离图表其余部分的顶部?