首页 > 解决方案 > 我们可以在 Altair 中绘制图像数据吗?

问题描述

我正在尝试在 altair 中绘制图像数据,特别是尝试在 Jake VDP 的书中的此链接中复制人脸识别示例 - https://jakevdp.github.io/PythonDataScienceHandbook/05.07-support-vector-machines.html

有人有幸在 altair 中绘制图像数据吗?

标签: pythonimshowaltair

解决方案


Altair 具有一个图像标记,如果您想绘制 URL 上可用的图像,可以使用该标记;例如:

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'
)

在此处输入图像描述

Altair 不太适合将二维数据数组显示为图像,因为该语法主要用于处理结构化表格数据。但是,可以使用flatten 变换窗口变换的组合。

这是一个使用您链接到的页面中的数据的示例:

import altair as alt
import pandas as pd
from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people(min_faces_per_person=60)

data = pd.DataFrame({
    'image': list(faces.images[:12])  # list of 2D arrays
})

alt.Chart(data).transform_window(
    index='count()'           # number each of the images
).transform_flatten(
    ['image']                 # extract rows from each image
).transform_window(
    row='count()',            # number the rows...
    groupby=['index']         # ...within each image
).transform_flatten(
    ['image']                 # extract the values from each row
).transform_window(
    column='count()',         # number the columns...
    groupby=['index', 'row']  # ...within each row & image
).mark_rect().encode(
    alt.X('column:O', axis=None),
    alt.Y('row:O', axis=None),
    alt.Color('image:Q',
        scale=alt.Scale(scheme=alt.SchemeParams('greys', extent=[1, 0])),
        legend=None
    ),
    alt.Facet('index:N', columns=4)
).properties(
    width=100,
    height=120
)

在此处输入图像描述


推荐阅读