图像#

图像标记允许将外部图像(例如图标或照片)包含在 Altair 可视化中。诸如 PNG 或 JPG 图像文件可以从提供的 URL 加载。

图像标记属性#

一个 image 标记可以包含任何标准标记属性和以下特殊属性

点击显示表格

属性

类型

描述

url

anyOf(URI, ExprRef)

图像标记的图像文件 URL。

aspect

anyOf(boolean, ExprRef)

是否保持图像标记的宽高比。

align

anyOf(Align, ExprRef)

文本或范围标记(area, bar, image, rect, rule)的水平对齐方式。可选值为 "left", "right", "center" 之一。

注意:范围标记支持表达式引用。

baseline

anyOf(TextBaseline, ExprRef)

对于文本标记,垂直文本基线。可选值为 "alphabetic"(默认值)、"top""middle""bottom""line-top""line-bottom" 之一,或提供有效值之一的表达式引用。"line-top""line-bottom" 值与 "top""bottom" 类似,但它们是相对于 lineHeight 计算的,而不是仅相对于 fontSize 计算。

对于范围标记,标记的垂直对齐方式。可选值为 "top", "middle", "bottom" 之一。

注意:范围标记支持表达式引用。

带有图像标记的散点图#

import altair as alt
import pandas as pd

source = pd.DataFrame.from_records(
    [
        {
            "x": 0.5,
            "y": 0.5,
            "img": "https://vega.github.io/vega-datasets/data/ffox.png",
        },
        {
            "x": 1.5,
            "y": 1.5,
            "img": "https://vega.github.io/vega-datasets/data/gimp.png",
        },
        {
            "x": 2.5,
            "y": 2.5,
            "img": "https://vega.github.io/vega-datasets/data/7zip.png",
        },
    ]
)

alt.Chart(source).mark_image(width=50, height=50).encode(x="x", y="y", url="img")

显示带有选择的图像标记#

此示例演示了如何使用拖动选择来显示图像标记。我们创建两个图表:一个使用点标记,另一个使用图像标记,仅将选择筛选器应用于后者。通过组合这两个图表,我们可以达到预期的效果。

import altair as alt
import pandas as pd

source = pd.DataFrame.from_records(
    [{'a': 1, 'b': 1, 'image': 'https://vega-altair.cn/_static/altair-logo-light.png'},
    {'a': 2, 'b': 2, 'image': 'https://avatars.githubusercontent.com/u/11796929?s=200&v=4'}]
)

brush = alt.selection_interval()
point = alt.Chart(source).mark_circle(size=100).encode(
    x='a',
    y='b',
).add_params(
    brush
)

img = alt.Chart(source).mark_image(width=50, height=75).encode(
    x='a',
    y='b',
    url='image'
).transform_filter(
    brush
)

point + img

在分层图表中,图像可能会相互重叠。另一种方法是在原始图表旁边使用分面图像图表。

img_faceted = alt.Chart(source, width=50, height=75).mark_image().encode(
    url='image'
).facet(
    alt.Facet('image', title='', header=alt.Header(labelFontSize=0))
).transform_filter(
    brush
)

point | img_faceted

如果我们希望图像在初始图表中不可见,可以在区间选择中添加 empty=False。然而,当进行选择时,Altair 不会自动调整图表区域以包含分面图表,这意味着选择看起来没有效果。为了自动调整图表大小,我们需要在 configure 方法中显式设置 autosize 选项。

brush = alt.selection_interval(empty=False)
point = alt.Chart(source).mark_circle(size=100).encode(
    x='a',
    y='b',
).add_params(
    brush
)
img_faceted = alt.Chart(source, width=50, height=75).mark_image().encode(
    url='image'
).facet(
    alt.Facet('image', title='', header=alt.Header(labelFontSize=0))
).transform_filter(
    brush
)

(point | img_faceted).configure(
    autosize=alt.AutoSizeParams(resize=True)
)

使用本地图像作为图像标记#

我们还可以通过先将本地图像转换为base64 编码字符串来显示它们。在下面的示例中,我们加载了 Altair 仓库中保存的两张图像;您可以将下面的图像路径替换为您机器上所需图像的位置。此方法也适用于存储为 Numpy 数组的图像,如教程在工具提示中显示 Numpy 图像所示。

import base64
import altair as alt
import pandas as pd

from io import BytesIO
from PIL import Image


image_paths = ["doc/_static/gray-square.png","doc/_static/altair-logo-light.png"]
base64_images = []

for image_path in image_paths:
    pil_image = Image.open(image_path)
    output = BytesIO()
    pil_image.save(output, format='PNG')
    base64_images.append(
        "data:image/png;base64," + base64.b64encode(output.getvalue()).decode()
    )

source = pd.DataFrame({"x": [1, 2], "y": [1, 2], "image": base64_images})
alt.Chart(source).mark_image(
    width=50,
    height=50
).encode(
    x='x',
    y='y',
    url='image'
)

图像工具提示#

此示例展示了如何在工具提示中渲染图像。可以使用 URL 或本地文件路径来引用图像。要渲染图像,您必须在数据中使用特殊的列名“image”,并将其作为列表传递给工具提示编码。

import altair as alt
import pandas as pd

source = pd.DataFrame.from_records(
    [{'a': 1, 'b': 1, 'image': 'https://vega-altair.cn/_static/altair-logo-light.png'},
     {'a': 2, 'b': 2, 'image': 'https://avatars.githubusercontent.com/u/11796929?s=200&v=4'}]
)

alt.Chart(source).mark_circle(size=200).encode(
    x='a',
    y='b',
    tooltip=['image']  # Must be a list containing a field called "image"
)