🏠 back to Observable

Is it possible to feed a Danfojs Series to data()?

For no particular reason, I wonder if it is at all possible to use DanfoJS Series object as my binding data() entry point?

Here is what I have so far

And here is my code:

function render(svg) {
      //   const xValue = d => d['Population (2020)'];
      //   const yValue = d => d['Country (or dependency)'];

  //   const xExtent = d3.extent(world_population, xValue);
  //   const xScale = d3
  //     .scaleLinear()
  //     .domain(xExtent)
  //     .range([0, width]);

  //   const yScale = d3
  //     .scaleBand()
  //     .domain(world_population.map(yValue))
  //     .range([0, height]);

  const xValue = d => d.data;
  const yValue = d => d.index;

  const xExtent = d3.extent(plot_data.values);
  const xScale = d3
    .scaleLinear()
    .domain(xExtent)
    .range([0, width]);

  const yScale = d3
    .scaleBand()
    .domain(plot_data.index)
    .range([0, height]);

  const selection = d3.select(svg);
  selection
    .selectAll('rect')
    .data(plot_data)
    .enter()
    .append('rect')
    .attr('fill', 'slateblue')
    .attr('y', d => yScale(d.index))
    .attr('width', d => xScale(d.data))
    .attr('height', yScale.bandwidth());
}

Any help will be much appreciated

After spending some more time looking at the Series Danfojs object it looks like I’ll need to transform the data to an object key/value pair in order for it to work, unless I’m overlooking something …

OK here is what I did, created an array of objects by mapping the Series to a new array of objects like so:

bind_data = plot_data.index.map((d, i) => ({
    ['index']: d,
    ['values']: plot_data.values[i]
}))

and my render function now looks like this:

function render(svg) {
    const xValue = d => d.values;
    const yValue = d => d.index;
    const xExtent = d3.extent(bind_data.map(xValue));
    const xScale = d3
        .scaleLinear()
        .domain(xExtent)
        .range([0, width]);

    const yScale = d3
        .scaleBand()
        .domain(bind_data.map(yValue))
        .range([0, height]);

    const selection = d3.select(svg);
    selection
        .selectAll('rect')
        .data(bind_data)
        .enter()
        .append('rect')
        .attr('fill', 'slateblue')
        .attr('y', d => yScale(yValue(d)))
        .attr('width', d => xScale(xValue(d)))
        .attr('height', yScale.bandwidth());
    }

After all this I don’t know if it is worth using Series as my data structure but at least I know how to convert them to a format I can use to render data. WIN!

1 Like