1

我正在使用 ObservableHQ 和 vega lite API 进行数据可视化,但遇到了一个我无法弄清楚的问题。问题是,我想从以下数据结构访问数据对象,

大批

  • 大批
  • 大批
    • 物品
    • 物品
  • 大批

正如您在我糟糕的绘图中看到的那样,我有一个多维数组,并且想从主数组中访问一个特定的数组。如何使用 Vegalite API 做到这一点?

vl.markCircle({
  thickness: 4,
  bandSize: 2
})
.data(diff[0])
.encode(
vl.x().fieldQ("mins").scale({ domain: [-60, 60] }),
vl.color().fieldN('type').scale({ range: ['#636363', '#f03b20'] }),
)
.config({bandSize: 10})
.width(600)
.height(40)
.render()

谢谢,

4

1 回答 1

1

Based on your comments, I’m assuming that you’re trying to automatically chart all of the nested arrays (separately), not just one of them. And based on your chart code, I’m assuming that your data looks sorta like this:

const diff = [
  [
    { mins: 38, type: "Type B" },
    { mins: 30, type: "Type B" },
    { mins: 28, type: "Type A" },
    …
  ],
  [
    { mins: 20, type: "Type B" },
    { mins: 17, type: "Type A" },
    { mins: 19, type: "Type A" },
    …
  ],
  …
];

First, flatten all the arrays into one big array, and record which array each came from with a new array property on the item object, with flatMap. If each child array represents, say, a different city, or a different year, or a different person collecting the data, you could replace array: i with something more meaningful about the data.

const flat = diff.flatMap((arr, i) => arr.map((d) => ({ ...d, array: i })));

Then use Vega-Lite’s “faceting” (documentation, Observable tutorial and examples) to make split the chart into sections, one for each value of array: i, with shared scales. This just adds one line to your example:

vl
  .markCircle({
    thickness: 4,
    bandSize: 2
  })
  .data(flat)
  .encode(
    vl.row().fieldN("array"), // this line is new
    vl
      .x()
      .fieldQ("mins")
      .scale({ domain: [-60, 60] }),
    vl
      .color()
      .fieldN("type")
      .scale({ range: ["#636363", "#f03b20"] })
  )
  .config({ bandSize: 10 })
  .width(600)
  .height(40)
  .render()

Here’s an Observable notebook with examples of this working. As I show there at the bottom, you can also map over your array to make a totally separate chart for each nested array.

于 2021-08-23T00:54:15.137 回答