You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Altair 4中使mark_rect生成的矩形居中于图像标记

Altair 4 实现矩形在图像标记后方居中显示的问题解决

问题背景

我使用Altair 4版本,目标是生成可通过关键词输入高亮匹配图像的图表(该功能仍在开发中),当前仅需实现mark_rect生成的矩形居中显示在mark_image标记后方。mark_image将通过x、y变量编码图片URL,mark_rect需使用与mark_image相同的x、y值,让矩形围绕这些x、y值居中。

尝试的错误代码

我曾尝试以下代码但未成功:

import altair as alt
import pandas as pd

data = pd.DataFrame({
        'x': [10, 20, 30, 40],
        'y': [5, 15, 25, 35]
                   })

# 仅作为测试示例,后续会替换为mark_image
base = alt.Chart(data).mark_point(width=500,height=500,
                                  color = 'red'
                                 ).encode(alt.X('x'), alt.Y('y'))

# 此处需要解决的部分
rect = base.mark_rect().encode(
                  x=alt.X('x:Q', axis=None),
                  y=alt.Y('y:Q', axis=None),
                  x2=alt.X2('x:Q', scale=alt.Scale(zero=False)),
                  y2=alt.Y2('y:Q', scale=alt.Scale(zero=False))                       
                  )

base + rect

错误信息

运行上述代码后出现以下报错:

SchemaValidationError: Invalid specification

        altair.vegalite.v4.schema.channels.X2, validating 'additionalProperties'

        Additional properties are not allowed ('scale', 'offset' were unexpected)

解决代码

更新后的代码可解决该问题:

rect = base.mark_rect(height = 50, width = 60).encode(alt.X('x'), 
alt.Y('y'))

内容的提问来源于stack exchange,提问作者chris_diaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:42:40