/r/d3js

Photograph via snooOG

A subreddit for discussing d3.js. d3, short for Data Driven Documents, is a javascript library for building documents from data sets. It's commonly used for data visualization but is not a graphing library. It's more than that and less than that.

If your post doesn't appear in the new queue after submission, send a message to the mods.

/r/d3js

5,925 Subscribers

7

Looking for some feedback on D3 visualization

I'm working on a D3 visualization for automatically generating maps based on data from a real estate app I'm building, would this group mind offering some thoughts on how I can improve this? I think its mostly done, but I'm super unfamiliar with good D3 practices and would love to leverage these experts.

You can see a live demo of the map here.

10 Comments
2025/01/30
20:04 UTC

1

Stack value typescript error is confusing, don't understand what is wrong

Hi I need some help with using typescript on this setup, I am following the example for stacked bar char and trying to implement it using TS. The code does work but the error does not make sense to me.

This is the code:

https://preview.redd.it/13z0z47uk5ge1.png?width=940&format=png&auto=webp&s=670c1d86363c6f1f0949890ab484a4e980349b9b

Line 16 throws this error at [, D]:

Type '{ [key: string]: number; }' must have a '[Symbol.iterator]()' method that returns an iterator. ts-plugin(2488)

and line 17 throws this error:

Argument of type 'InternMap<number, InternMap<string, Data>>' is not assignable to parameter of type 'Iterable<{ [key: string]: number; }>'.   The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.     Type 'IteratorResult<[number, InternMap<string, Data>], undefined>' is not assignable to type 'IteratorResult<{ [key: string]: number; }, any>'.       Type 'IteratorYieldResult<[number, InternMap<string, Data>]>' is not assignable to type 'IteratorResult<{ [key: string]: number; }, any>'.         Type 'IteratorYieldResult<[number, InternMap<string, Data>]>' is not assignable to type 'IteratorYieldResult<{ [key: string]: number; }>'.           Type '[number, InternMap<string, Data>]' is not assignable to type '{ [key: string]: number; }'.             Index signature for type 'string' is missing in type '[number, InternMap<string, Data>]'. ts-plugin(2345)

Despite the TS errors this code is functional, does anyone know the best or the correct way to use D3 and TS?

1 Comment
2025/01/30
15:56 UTC

1

Anyone know if this stock price chart with auto-updating scale was made with D3.js?

Hi everyone,

I’ve been looking for a YouTube video that features a chart showing the evolution of a stock price, with an auto-updating scale as the price changes :
https://www.youtube.com/shorts/o-5Hn26CD24

I’m wondering if this visualization was created using D3.js. If so, does anyone know where I could find the source code for it?

If it wasn’t made with D3.js, could anyone point me to the website, software, or programming language that might have been used to create such a chart?

Thanks in advance for your help!

2 Comments
2025/01/28
22:14 UTC

49

Making an audio-reactive visual with p5, d3, Three,js, and Ableton.

6 Comments
2025/01/20
20:33 UTC

3

In d3.js v^7.9.0 zoom functionality I am having an issue where when I click to zoom out/zoom in, the chart goes out of the viewport instantly (need to recenter or pan to see the chart again)

  const svg = d3
      .select(svgDomRef.current)
      .attr("width", containerWidth)
      .attr("height", containerHeight)
      .attr("style", "max-width: 100%; height: auto; user-select: none;");

    const g = svg.append("g");

    const zoom = d3
      .zoom()
      .scaleExtent([0.5, 5])
      .on("zoom", function (event) {
        g.attr("transform", event.transform);
      });

    svg.call(zoom as any).on("click", null);

    svg.call(
      zoom.transform as any,
      d3.zoomIdentity.translate(100, containerHeight / 3)
    );

1 Comment
2025/01/13
05:18 UTC

1

How do I add labels on my line chart?

https://codepen.io/pen?template=jOgVOOV

Here is the code to my line chart.

I tried adding something like this, but it doesn't seem to work.

svg
  .selectAll("text")
  .data(dataset)
  .enter()
  .append("text")
  .text(function (d) {
    return d.value;
  })
  .attr("y", function (d) {
    return y(d.value) - 5;
  })
  .attr("x", function (d) {
    return x(d.date);
  })
  .attr("fill", "#A64C38");
2 Comments
2025/01/12
21:39 UTC

1

D3 Graphviz Pan/Zoom

I have a D3 graphviz layout that creates an SVG, with a top level g and then a bunch of nested SVG objects representing nodes. I'm essentially looking to build a "node tour" visualization, of a hierarchy (Footballing movement patterns...) from the root all the way down to the leaf.

Using D3-zoom, I can pan (translate) and zoom (scale) to a node the first time. When I don't scale it will pan to each node successfully. When I add the scale back in, it goes haywire against the second node.

Anyone have an effective algorithm/example for something like this? Basically I'm trying to pan/zoom to a node so that the node fills a consistent majority of the viewport... When it's transform is complete/render.is complete increment an index and move to the pan/zoom next node (perhaps zooming out a hair between nodes).

1 Comment
2025/01/12
17:52 UTC

27

I Made a GUI for the Tinkerer's Workshop in Terraria with d3.js

I used d3.js for the crafting trees, and it worked out wonderfully!

I made a video detailing the development process, if anyone is curious: https://youtu.be/D3qQfvJMpwY?si=_J-JANVv72pb-sX3

Here's the link to Tinkery: https://littlestring.github.io/Tinkery

Here's the link to the repo: https://github.com/LittleString/Tinkery

1 Comment
2025/01/02
20:57 UTC

5

Making an interactive map for a personal project

I wanted to put scales on my map which changes dynamically as I zoom and put grids with longitudes and latitudes which change as I zoom and pan. But being a beginner in d3, I dont seem to configure much. I want to look at examples but there seem to be very limited material. I was wondering if anyone could provide an example project so I can learn from it.

3 Comments
2024/12/26
15:37 UTC

6

Research on Graph Visualization Tools

Hi everyone,

I’m conducting a quick survey to gather feedback on graph visualization libraries and the features that matter most to users. Whether you’re a student, developer, data scientist, product manager etc. your insights would be incredibly valuable in helping improve tools for exploring and analyzing complex datasets.

The survey is short (just 3-5 minutes) and focuses on understanding what you look for in a graph visualization library.

Here’s the link to the survey: [Link]

Thank you so much!

0 Comments
2024/12/09
10:22 UTC

3

Advice needed: How can I minimize movement in this animated circle pack timeline visual tracking asset ownership? Excessive rearrangement between snapshots makes asset transfers hard to follow.

3 Comments
2024/12/02
17:57 UTC

2

Looking for an example of an Org Chart updating from data returned.

Hi I'm struggling with making the Org Chart functionality work. I have it posting data back to the server with the results from drag and drop. I'd like to be able to reload the screen with different data on command from the server.

Does anyone have an example of this functionality?
Thanks

0 Comments
2024/11/20
15:00 UTC

1

Tooltip: Table + Chart

I want to display a table and a chart in my tooltip. How can I achieve it? Is there any current example (not the usa states thing!) where I can look how to achieve that?

1 Comment
2024/11/11
16:24 UTC

2

Too many LineStrings for SVG?

I'm currently creating a map of Pompeii and I am facing the issue that SVG can't render all my Lines (101k). I want the map to SVG but I never faced an issue like this before, does anybody know about a solution? Many Thanks in advance!

SVG

CANVAS

2 Comments
2024/11/04
19:29 UTC

9

OBLSK.10 // Enclosing Pack Data with MIDI—visualised in P5 and D3

1 Comment
2024/10/25
17:48 UTC

2

Need help, can't visualize in browser.

Hey, I'm starting with d3, I am following the steps this guy is making https://youtu.be/y7DxbW9nwmo?si=SfLy8nRTDBRT0jG5 but It does not say how to make the library work in VSC. Sorry about my english I'm from Argentina, loll.

8 Comments
2024/09/12
12:04 UTC

6

Looking for D3js Developer

D3js + React Developer needed. Need to develop a graphic visualization tool that does not currently exist / does not have a template.

The format of the input data is standardized but there are hundreds of combinations of the data that impacts the visualization. It's a professional industry graph / chart that is used frequently but done manually either in Excel, PowerPoint or even on paper. To reference existing examples on D3js, its like a mix of a Bar Chart & tree map.

Alongside the visualization (on the right of the graph/chart) there is some math that needs to be displayed but its very simple addition / multiplication. I have a 2-3 page document explaining the industry, the process, and logic required to create it as well as several manually created copies.

DM me if interested, either contract work or full-time if you are also a full-stack js developer. (Nodejs, React)

Firm setup in US & Canada, although am able to hire remotely.

6 Comments
2024/09/10
15:47 UTC

2

How would one make a cartesian plane?

So I have this array of simple coordinates [{X:2,y:3},{x:-4:,y:7}...], only x and y axis, both positive and negative integers, if you've ever been to school you know what a cartesian plane looks like. How can I make it in javascipt? I heard of d3js but have only found tutorials on classic charts or trees, so that's why I'm here, a little help anyone?
P.s. to be more specific, I want to have a square plane of squares and every coordinate that I don't have is a white square, but as soon as I add a coordinate it colors the appropriate square in red.

4 Comments
2024/09/09
01:13 UTC

4

Good React.js D3 course? 2021 or the 2022 course from freecode camp?

Hi. I am looking for a good React.js D3 course. I am currently watching the 2021 one, but I am not sure the 2022 one is good. Any other video that is better than those? Thank you for answering.

2 Comments
2024/08/30
17:07 UTC

1

Extracting data from Interactive Node Tree

I am making an interactive where the user can add nodes and put data.

My question is:

Is it possible that we can do the reverse? From Interactive Node Tree (which will be inputed by the user) to data(CSV,JSON,etc).

I need to extract the data inputed by user and its parent node.

0 Comments
2024/08/26
09:53 UTC

3

World Map using D3.js

Hey all !
I am about to propose a project for my university which will take tweets during disasters and extract the locations from it which might be for help, food supply, accidents or any other incidents.
I just wanted to know is it possible to show the coordinates of address using D3js.
I have little amount of time to try it out and check it. If any of you guys know about this please do clarify me on this

1 Comment
2024/08/26
05:55 UTC

5

I made rendering-engine named flitter: seeking community feedback

I've been working on a project called Flitter, a JavaScript rendering engine inspired by Flutter, and I'd love to get your thoughts on it. (docs: https://flitter.dev)

I wrote a post: https://medium.com/@wjdwoeotmd/05e61c3e2f72

|| || ||

0 Comments
2024/08/25
09:39 UTC

2

How to read <svg> data into javascript

Attached is an excerpt from my first d3 file. A lot of the coding depends on the chart width and height, here 600 as below:

Since the <svg> is not within the <script> tags and is not javascript, how to I read width and height into javascript to avoid re-inputting every time I change something? For instance when generating initial coordinates, (array pos[]), I have had to insert 600 instead of reading width from <svg>. Thanks.

<body>

<svg id="chart" width="600" height="600"></svg>

<script> let maxAnts = 200; let pos = \[\]; let jump = 10; for (let i = 0; i < maxAnts; i++) { pos\[i\] = \[\]; for (let j = 0; j < 2; j++) { pos\[i\]\[j\] = Math.floor(1 + Math.random() \* 600); } } (more coding ...) </script> </body>
1 Comment
2024/08/19
04:06 UTC

7

Interactive network graph UI

Hello I'm building a UI for my SvelteKit web-app and I am on a hunt for the perfect graph-visualization library (example of what I mean). Perhaps you may be able to share some (svelte-specific) feedback, resources, or experiences you've had to help me on my way.

I used my shitty smartphone to assess 'snappy-ness' of the libraries mentioned.


Desired use-case:

  • Visualize network graph of 10-100 nodes (maybe 1000 max at very few occasions)
  • Interactivity, drag, drop, hover, click and press/hold
  • Updateable: the graph visualization should be updated when user makes a change or gets some new data (e.g. draw new edge or add several nodes) without completely disorienting the user
  • Snappy: both on desktop and mobile
  • Customizatble style: nodes and edges should be styled in specific ways (e.g. user avatar in the node)
  • Customizable interactivity: custom behaviour through user-interaction (e.g. shadcn popover when clicking a node)

What I found so far:

  • Svelvet: this one is svelte-tailored and seems to have good interactivity/customizability but it's not really designed for graph-visualization and I'm unable to find many examples to sell me on feasibility with regard to the 'updateable' aspect. The few examples I could find don't very snappy (compared to some of the others)
  • Sigma.js: Uses WebGL and has recently been updated so may be more performant for larger graphs though they mention themselves this makes it difficult to customize
  • D3 with d3-force or with cola.js: D3 seems to be very customizable though I'm still iffy on whether I will be able to implement custom UI component on top of the nodes. Using cola as optimization algorithm seems to really improve snappy-ness
  • Cytoscape with cola.js this one seems the best at first glance: snappy, no unneccesary motion after initial placement of the nodes, good UX on mobile, cool features such as the bounding boxes... but the repo hasn't been touched in 2 years
  • Force graph this one has very nice demo's and the desired 'incremental update' feature. This may be my go-to pick so far.
  • Vis.js network this one also looks very snappy and may be a good contendor to Force graph
2 Comments
2024/08/05
10:58 UTC

3

How to setup d3 with npm ....

Is there an example of how to install and setup d3 using npm , the instruction on main page do not work ...

The suggested way of importing d3 after installing it with npm

import * as d3 from "d3"

results in

"TypeError: Failed to resolve module specifier "d3". Relative references must start with either "/", "./", or "../".

Im facing similar issue as was reported 6 years ago in following article:

https://stackoverflow.com/questions/48471651/es6-module-import-of-d3-4-x-fails

Yet on the main page of d3 there is ZERO mentioning of workarounds that described in the above post... so am I missing something???

thank you for your help.

Regards...

0 Comments
2024/07/16
00:54 UTC

5

how do I space up nodes in hirerical data tree diagram?

hello, I have hirerical data and I made a tree diagram to show it , how do I space up each node so that it will look better

https://preview.redd.it/t7qwlbgsavad1.png?width=1920&format=png&auto=webp&s=03f2a1ddc364650674d0be6e3524f831bc679d10

this is just an example of how it looks now
as you can see it looks bad ,each circle is too close to each other
I could just increase the width
but then users will have to use the scrollbars to navigate and i dont really want it , I want the tree to be shown all clearly at once
with gap between each circle, this is my code.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tree Diagram</title>
    <link rel="stylesheet" href="static/css/styles.css" />
    <script src="static/js/d3.v7.js"></script>
  </head>
  <body>
    <div class="canvas"></div>

    <script>
      const dims = { height: 1000, width: 2000 }; // Further increased dimensions

      const svg = d3
        .select(".canvas")
        .append("svg")
        .attr("width", dims.width + 100)
        .attr("height", dims.height + 100);

      const graph = svg.append("g").attr("transform", "translate(50, 50)");

      // tree and stratify
      const stratify = d3
        .stratify()
        .id((d) => d.id)
        .parentId((d) => d.parent);

      const tree = d3
        .tree()
        .size([dims.width, dims.height])
        .separation((a, b) => (a.parent == b.parent ? 3 : 4)); // Further increased separation

      // update function
      const update = (data) => {
        // remove current nodes
        graph.selectAll(".node").remove();
        graph.selectAll(".link").remove();

        // get updated root Node data
        const rootNode = stratify(data);
        const treeData = tree(rootNode).descendants();

        // get nodes selection and join data
        const nodes = graph.selectAll(".node").data(treeData);

        // get link selection and join new data
        const link = graph.selectAll(".link").data(tree(rootNode).links());

        // enter new links
        link
          .enter()
          .append("path")
          .transition()
          .duration(300)
          .attr("class", "link")
          .attr("fill", "none")
          .attr("stroke", "#aaa")
          .attr("stroke-width", 2)
          .attr(
            "d",
            d3
              .linkVertical()
              .x((d) => d.x)
              .y((d) => d.y)
          );

        // create enter node groups
        const enterNodes = nodes
          .enter()
          .append("g")
          .attr("class", "node")
          .attr("transform", (d) => `translate(${d.x}, ${d.y})`);

        // append circles to enter nodes
        enterNodes
          .append("circle")
          .attr("fill", (d) => {
            if (d.data.status === "up") return "#69b3a2"; // Green
            if (d.data.status === "down") return "#ff4c4c"; // Red
            if (d.data.status === "tempup") return "#ffa500"; // Orange
            if (d.data.status === "tempdown") return "#c0c0c0"; // Silver
            return "#aaa"; // Default color
          })
          .attr("stroke", "#555")
          .attr("stroke-width", 2)
          .attr("r", 20)
          .style("filter", "drop-shadow(2px 2px 5px rgba(0,0,0,0.2))"); // Add shadow for modern look

        enterNodes
          .append("text")
          .attr("text-anchor", "middle")
          .attr("dy", 5)
          .attr("fill", "white")
          .style("font-family", "Arial, sans-serif")
          .style("font-size", "12px")
          .text((d) => d.data.name);
      };

      // data fetching function
      const fetchData = async () => {
        try {
          const response = await fetch("http://127.0.0.1:80/api/data");
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          const data = await response.json();
          console.log(data);
          update(data);
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      };

      // fetch data initially
      fetchData();
    </script>
  </body>
</html>
0 Comments
2024/07/06
09:32 UTC

Back To Top