d3js v4使用内置的堆栈功能生成区域

时间:2019-01-30 12:22:15

标签: javascript typescript d3.js

我正在尝试使用d3js制作堆叠图。

目前,我有一个类似如下的代码:

...
interface IFakeData {
      name: string,
      date: Date,
      nbrOfMessages: number      
    }


function makeFakeData():IFakeData[]{
  return [
    { name: "John", date: new Date(2015, 1, 1), nbrOfMessages: 1 },
    { name: "John", date: new Date(2015, 2, 1), nbrOfMessages: 2 },
    { name: "John", date: new Date(2015, 3, 1), nbrOfMessages: 3 },
    { name: "John", date: new Date(2015, 4, 1), nbrOfMessages: 4 },
    { name: "Alice", date: new Date(2015, 1, 1), nbrOfMessages: 10 },
    { name: "Alice", date: new Date(2015, 2, 1), nbrOfMessages: 3 },
    { name: "Alice", date: new Date(2015, 3, 1), nbrOfMessages: 5 },
    { name: "Alice", date: new Date(2015, 4, 1), nbrOfMessages: 1 },
    { name: "Bob", date: new Date(2015, 1, 1), nbrOfMessages: 5 },
    { name: "Bob", date: new Date(2015, 2, 1), nbrOfMessages: 8 },
    { name: "Bob", date: new Date(2015, 3, 1), nbrOfMessages: 9 },
    { name: "Bob", date: new Date(2015, 4, 1), nbrOfMessages: 10 }        
  ]
}   

const messages = makeFakeData();
const color = d3.scaleOrdinal(d3.schemeCategory10);
const trobador = d3.nest<IFakeData, IFakeData>()
  .key(d=>d.name)      
  .entries(messages)


const stack = d3.stack()
  .keys(trobador.map(e=>e.key))
  .order(d3.stackOrderNone)
  .offset(d3.stackOffsetNone);

let matrix:IFakeData[][] = trobador.map(e => e.values)
let transposed = d3.transpose<IFakeData>(matrix)
let finalData = transposed(e => {
      let result = {} as any
      e.forEach(v => {
        result[v.name]=v.nbrOfMessages
      })
      return result
    })

const ariel = d3.area()
  .x((d,i)=>xxx(i))
  .y0(d => yyy(d[0]))
  .y1(d => yyy(d[1]))


然后我正在尝试像这样堆叠:

let path = d3.select(svgElement)
.append("g")
.selectAll("path")
data(stack(finalData))
.enter()        
.append("path")            
.attr("d", ariel)
.style("fill", d => color(d.key))    

我收到以下错误:

  

类型'Area <[数字,数字]>'的参数不可分配给   'ValueFn类型的参数,字符串|编号布尔| null>”。种类   参数“数据”和“基准”不兼容。       输入'Series <{[key:string]:number; },string>'不可分配给'[number,number] []'类型。         属性“ pop”的类型不兼容。           类型'()=> SeriesPoint <{[键:字符串]:数字; }> | undefined'不能分配给类型'()=> [number,number] |   未定义”。

我已经尝试过转换数据,并在线检查了很多教程,例如: https://bl.ocks.org/lorenzopub/0b09968e3d4970d845a5f45ed25595bbhttps://bl.ocks.org/mbostock/b5935342c6d21928111928401e2c8608https://bl.ocks.org/DimsumPanda/689368252f55179e12185e13c5ed1feehttps://bl.ocks.org/mbostock/3020685https://beta.observablehq.com/@mbostock/d3-stacked-area-chart 等等...但是我没有找到任何解决方案。

我目前可以使用d3js(v4)来创建区域,但是由于我不使用堆栈,因此这些区域会重叠。我的解决方案是使用堆栈函数尝试解决此问题。

0 个答案:

没有答案