How to include csv data using `var data = d3.csvParse(csvdata, type)`?

Hey Aaron,

Sure, no problem - to break this down in to a few parts:

I have been trying ways to include var data = d3.csvParse(csvdata, type); in to the javascript, but get errors like TypeError: t.charCodeAt is not a function.

You’ve defined a cell (correctly) that parses a string into an array of objects using the d3.csvParse method, and assigns the resulting array of objects to the variable csvdata. Calling d3.csvParse(csvdata) is unnecessary, then, later on - it’s already a parsed array of objects, so calling csvParse on it throws this error. csvParse expects a string as input (with a String#charCodeAt method), rather than an array.

Re: constructing HTML - cells like

html`<body>
`

Unfortunately aren’t going to work, for a few reasons:

  • the html tagged template literal is less of a “write this to the page” method as a “create an element like this”, so if you give it just a starting tag like <body>, it’ll generate an empty <body> element rather than starting an element that later blocks can fill.
  • The other difficulty here is that cells don’t run in visual order: cells run when they need to based on their dependencies.
  • There’s already a body tag: notebooks render into a page that already has <html>, <meta>, and <body> tags, so trying to add another body in that body won’t be okay in HTML’s rules.

Here’s a tweaked, working example: Learning A Donut Chart from D3.js / Tom MacWright | Observable

The main changes to the chart cell are:

  • Observable is all about returning elements as values: so the chart cell itself creates an svg element and returns it: that’s how the chart is displayed from that cell. This is a bit different than web coding where you’ll primarily rely on selectors like d3.select('body') to add things to the page (but pretty similar to systems like React, Backbone, and so on where components create their own elements.
  • That Stackoverflow ticket seemed to be a bit off - scale.ordinal in d3 v3 is scaleOrdinal in d3 v4.

Hope that helps! Totally appreciate that it’s a steep learning curve - it’s easy to get lost in corners when learning a new thing. I feel the same way when I’m trying to learn Rust and some other languages… can get caught on ‘adding two numbers together’ for hours :slight_smile:

1 Like