python - 交互式 Altair 绘图轴上方的文本
问题描述
一段时间以来,我一直在遵循有关问题的建议,将各种提示/信息放在我在 Altair 的地块上。但是,如果 Altair 绘图设置为 interactive(),则此建议不起作用 - 在我看来,启用比例绑定可防止任何绘图对象出现在矩形轴之外。
这是一个基于该链接的复制示例:比较生成的图有/没有最后注释的 interactive() 行。
import altair as alt
import pandas as pd
import numpy as np
df = pd.DataFrame({'x': np.linspace(0, 4, 1000)})
df['y'] = np.sin(2 * np.pi * 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)
text1 = alt.Chart(df, width=600, height=400).mark_text(
align='left', baseline='bottom', dx=+5, fontSize=12,
).encode(
x=alt.value(0.0),
y=alt.value(-1),
text='_label:N',
opacity=alt.condition(select_point, alt.value(1.0), alt.value(0.0)),
).transform_calculate(
_label='"ABOVE AXES x = " + format(datum.x, ".2f") + ", y = " + format(datum.y, ".2f")',
)
text2 = alt.Chart(df, width=600, height=400).mark_text(
align='left', baseline='bottom', dx=+5, fontSize=12,
).encode(
x=alt.value(0.0),
y=alt.value(12),
text='_label:N',
opacity=alt.condition(select_point, alt.value(1.0), alt.value(0.0)),
).transform_calculate(
_label='"INSIDE AXES x = " + format(datum.x, ".2f") + ", y = " + format(datum.y, ".2f")',
)
chart = alt.layer(line, points, text1, text2)
# chart = chart.interactive()
附加信息,以防有帮助/相关:
- 我使用interactive() 和手动选择比例绑定对此进行了测试,效果相同
- 将图表保存为 HTML 后,我在 PyQT WebEngineView 容器中进行渲染
- 肯定会在轴边界之外对对象进行某种跟踪,即使它们未在交互式 ON 的情况下显示。我还用点标记进行了测试:悬挂在轴边界边缘的大标记在交互式关闭时完全可见,但在交互式打开时会被切断。但是,如果您启用了交互式并缓慢拖动轴边界,您可以看到绘图标题向上移动以避免大标记从绘图的顶部边缘滑落,直到标记的中心离开边界和标题弹回来。
底线问题:当绘图设置为交互式时,如何让文本出现在 Altair 的轴边界之外?
解决方案
传递clip=False
到mark_text()
,文本将在轴外可见。
对于非绑定比例和绑定比例,该clip
参数默认为。False
True
推荐阅读
- ethereum - 检索卡在智能合约上的以太币
- sql-server - IF...ELSE 条件总是返回 ELSE 条件
- python - Python 类方法执行多次
- haskell - 在haskell中使用泛型列出构造函数名称
- java - java如何区分Lambda中的Callable和Runnable?
- python - 如何仅打印工作日(不是周末)的日期范围内的日期范围内的月份?
- r - R - 计算不同时间间隔之间的运行总计
- sql - SQL 使用过滤器将行连接成一个字段 (DB2)
- javascript - HTML(或 jQuery):选择一个或两个复选框(或单选按钮)
- html - 发布项目后 CSS 不加载