我们可以在Altair中绘制图像数据吗?


Answers:


16

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不太适合像图像一样显示二维数据数组,因为语法主要设计用于结构化表格数据。但是,可以结合使用扁平化变换窗口变换

以下是使用您链接到的页面中的数据的示例:

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
)

在此处输入图片说明


谢谢@jakevdp。您和您的书都很棒。我们是否可以期待altair-viz中的新功能,这些新功能将使我们能够直接从numpy数组中可视化数据,而不必将其转换为pandas数据框,还是我们将不得不长期依赖matplotlib?
arjan-hada

不,Altair的语法与结构化的表格数据紧密相关。我预计不会支持指定为无标签多维数组的数据。
jakevdp
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.