Questions about D3 force layout when modifying data

Dear Community,

I am learning how to modify data while generating the d3-force layout. I was referring to observable-modifying-a-force-directed-graph and blocks-modifying-a-force-layout to learn that. I have questions when I read both:

  1. In the observable example, how the function update is used? There is one cell declare update but it is undefined as there is no return. Is it used in the chart’s declaration?. I also can see chart.update but I could not see function update() {} in the chart’s cell. And how the update in the Object.assign() is used? Is it the update undefined? If not where does this update come from? I am really baffled by this update function in both cells…
  2. I am comparing two references. The way they implement refresh is quite different. Is it because the runtime environment for Observable is different? Is it because the notebook is "observable“ so that the update function will be observed and thus the animation will be applied? I feel without Observable’s running environment, I have to use the tech provided by the second reference. Is that correct?

Sorry I am pretty new to Observable and D3, and even JS. I would be grateful if you could help me.

Thank you very much!

Marvin

Hi Marvin,

The update() function is merged to the svg element chart,
image

that’s convenient, as chart cell value can be accessed from other cells. At the same time, the update() function has access to the scope variables from the chart visualization, such as link, node, and simulation. The idea is that you can call chart.update() with new data and the d3 code inside chart will take care of updating the visualization.

Here is the first update call
image

graph value is coming from the viewof graph cell. The few lines of code bellow are basically to set the selection radio input values inside a form element and a timer to update it at a certain interval. As Observablehq is a reactive environment, when viewof graph cell value is updated, the cell update = chart.update(graph) is also updated, thus making it animated.

viewof graph cell value is also linked to other notebook cells const graphs = {1: graph1, 2: graph2, 3: graph3};

This implementation is different from your blocks example because Observablehq environment takes care of updating and refreshing cells that are somehow connected.

I hope that helps. If you haven’t read this yet, these are great resources

1 Like

Hi Radames,

Thank you very much for the reply! I didn’t realize I can check the definition of the chart by calling the chart again. I used to think it will be view again. And the reason I didn’t think update in chart was a function is because there is no keyword function. But I checked after you replied and I learned that it is allowed in the JS.

Thank you very much for the reply again!

Marvin