首页 > 解决方案 > Altair-即重复和变换

问题描述

有没有办法使用重复图表使用的编码来应用数据转换或过滤?

如果我对文档的理解正确,它似乎是不可能的:

当前只能为行和列指定重复(例如,不能为层指定),并且目标只能是编码(例如,不能是数据转换),但是 Vega-Lite 社区内部正在讨论如何使这种模式在未来。

有什么好的方法可以解决这个问题?例如下面,假设我只想绘制y>0(或者可能是另一个变换,我不想只在 y 轴上缩放)的点。有没有办法使用重复目标来应用类似于第 0 行的东西(如第 1 行中所尝试的那样,但失败了TypeError: '>' not supported between instances of 'RepeatRef' and 'float')?

import altair as alt
import numpy as np
import pandas as pd

x = np.arange(100)
source = pd.DataFrame({
  'x': x,
  'f': np.sin(x / 5),
  'g': np.cos(x / 3),    
})

alt.Chart(source).mark_line().encode(
    alt.X('x', type='quantitative'),
    alt.Y(alt.repeat('column'), type='quantitative'),
).transform_filter(
    # alt.datum.f >= 0. #0 Works, but would like to use f or g depending on the plotted variable
    alt.repeat('column') > 0. #1 ERROR HERE
).repeat(
    column=['f', 'g']
)

标签: pythonaltair

解决方案


无法引用转换中的重复字段。解决此问题的最佳方法是通过串联构建图表;例如:

alt.hconcat(*(
  alt.Chart(source).mark_line().encode(
      alt.X('x', type='quantitative'),
      alt.Y(col, type='quantitative'),
  ).transform_filter(
      alt.datum[col] >= 0
  ) 
  for col in ['f', 'g']
))

在此处输入图像描述


推荐阅读