python - 我们可以在 Altair 中绘制图像数据吗?
问题描述
我正在尝试在 altair 中绘制图像数据,特别是尝试在 Jake VDP 的书中的此链接中复制人脸识别示例 - https://jakevdp.github.io/PythonDataScienceHandbook/05.07-support-vector-machines.html。
有人有幸在 altair 中绘制图像数据吗?
解决方案
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
)
推荐阅读
- reactjs - 根据用户权限显示菜单列表
- python - 如何计算采购订单行中每列的平均价格?
- c# - ActionFilterAttribute - 当顺序很重要时
- android - 小部件未返回 Future 的视图
颤振状态 - bash - 如何在 bash 中从 .txt 文件中读取参数
- spring - Spring Boot 不加载 javascript 文件
- genesys - 如何添加呼叫属性。通话结束后就像标记完成按钮一样?
- odoo - 如何在 Odoo 12 中自定义字段 tabindex
- linux - 如何将另一个脚本的输出编码为其他脚本中的条件
- ios - 如何在 Activity 选项卡中显示 IOS 后在 App Store 提交 App 以供审核