/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,798 Subscribers

8

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

5

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

4

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

8

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

6

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

5

Contract Work? Remote. Tutoring D3 or Front-end Dev.

Hi

Need an expert in d3.js to help build a real-time graph with custom animations.

The chart will move depending on a web-socket where data is fed in from.

This is needed in TS react application, frontend.

Currently we are using lightweight-charts but we need something more customisable and lower level.

tradingview/lightweight-charts: Performant financial charts built with HTML5 canvas (github.com)

Paid in CRYPTO or BACS.

0 Comments
2024/06/30
11:57 UTC

3

Any examples of a collapsible tree integrated in a React app?

Hello! I'm new to D3 and was able to recreate Mike Bostock's collapsible tree with plain javascript. But I'm having difficulty running this code in a React app. Are there any examples of D3 templates such as Collapsible Tree, Radial Tidy Tree, or Circle Packing working in a React environment? Thank you!!

5 Comments
2024/06/21
03:35 UTC

10

I created a graph to explain the D3 Scale API for anyone who finds it confusing, just like I did.

2 Comments
2024/06/20
02:47 UTC

4

D3 Community Gallery?

Are there any large web galleries of interactive visualizations? Looking for any site that has lots of examples to draw inspiration from for interactive visualizations. I think there used to be one on Observable before it became ObservableHQ+Observable Framework. Ideally D3, but doesn't need to be.

4 Comments
2024/06/16
17:26 UTC

4

Maps of Metal - Southeast Asia (d3.force, d3.geo)

1 Comment
2024/06/06
07:19 UTC

3

help requested/tutorial request - a network graph that changes over time

I've seen plenty of guides and examples on network graph and styling - I've also seen tutorials on animating stroke lines etc. But Is surprised how few examples there are on 'previous/next' style data visualisations.

I have two problems. Firstly my data. My graph needs to step through 200 days not unlike a powerpoint slide deck. Each day represents the instance of a node and a few new links. So an example of this could be describing users (approx 100) signing into a social network and making a few friends etc day they use it (a few only logging in once or twice and making very few friends!

At the moment I have set up as there being a different json file for each day, the files are small but I'd rather not have 200 separate files. (sorry if this an obvious answer but I honestly don't know how to do it another way).

My second problem is sometimes I want to 'clear the deck' of previous days data to isolate certain periods of time. For example if a new feature was added which could effect users behaviour (they decrease making friends). How do you think I should go about doing that?

All useful tutorials welcome.

4 Comments
2024/05/23
19:47 UTC

7

Discover Amazing Endemic Species - An Open-Source, Community-Driven Species-as-a-Service Application! 🌍🦎🌱

I’m excited to share with you all a project that’s making waves in the world of biodiversity and conservation – Amazing Endemic Species (AES)!

Websitehttps://aes.shenlu.me

Source codehttps://github.com/shenlu89/amazing-endemic-specie

https://reddit.com/link/1cyg6z0/video/6covjnueh32d1/player

1 Comment
2024/05/23
00:48 UTC

5

Any CMS out there that integrates nicely with D3?

Use-case: looking at building a data visualisation blog and assessing potential technologies.

Think more: data journalism (it's for a non-profit initiative) and less: dashboards for business intelligence.

The key output would be blogs containing (hopefully!) beautiful data visualisations, ideally interact-able to some extent by the end-users.

Observable Framework is nice but (relative to other things I've looked at) falls down a little on the blogging part of the picture. As an (eager!) beginner, there isn't really a theme collection to help get me started, and certainly none that are content publishing centric. Otherwise, it's pretty ideal.

Something like a CMS (assuming headless / static site generator) would be really helpful to get me started and the tighter the integration with D3 the better (by that I mean perhaps something like the ability to import it into a theme and maybe even a UI component for storing the visualisations).

I'm aware that D3 is challenging but ... I'm already learning a lot and am doing this to the best of my abilities.

Any recommendations for frameworks / CMSes that might be good fits very much appreciated!

2 Comments
2024/05/22
11:44 UTC

1

D3 selecting all but modifying based on external criteria

This is one of the things in d3 that always hangs me up. I have a rendered SVG with text labels. I want to modify some of the text labels by adding a footnote superscript to them. I want to do a selectall and store the elements in a variable. Then iterate over this variable and modify only certain elements based on their index in the selection. I have all of the logistics working except the ability to modify only certain elements from my selectall. I can modify all of the elements, but not just the second element in a selection that returns 3. For example.

Var TextElems = d3.selectAll(text) TextElems.append(tspan) //works TextElems[1].append(tspan) // doesn't work.

Is node what I'm looking for? TextElems[1].node().append(tspan)

2 Comments
2024/05/16
20:17 UTC

2

Panning is really laggy on a zoomable heatmap

Hey all ! I'm very new do d3 . I created a heatmap in React not long ago and everything is working perfectly except for one thing.
When the amount of data gets substential, The panning after zooming gets really laggy. I guess it's the amount of rectangle i'm drawing that's the cause, but I wanted to check with some more experienced people if there was a solution other than "redo it all in canvas"
Here's the function I'm using to zoom in and out :

const zoom = (svg: d3.Selection<any, unknown, null, undefined>) => {
        const extent = [[marginLeft, marginTop], [width - marginRight, height - marginTop]] as [[number, number], [number, number]];
        svg.call(d3.zoom()
            .scaleExtent([1, 8])
            .translateExtent(extent)
            .on("zoom", zoomed));

        function zoomed(event: any) {
            const labelSteps = calculateXLabel(event.transform.k * width / 120)
            const xAxis = d3
                .axisBottom(xScale)
                .tickValues(labelSteps);            
            xScale.range([marginLeft, width - marginRight].map(d => event.transform.applyX(d)));
            svg.selectAll<Element, dataItem>("rect.heatMapRect").attr("x", (d) => (xScale(d.x) || 0)).attr("width", xScale.bandwidth());
            if (xAxisWatcherRef.current) d3.select(xAxisWatcherRef.current).call(xAxis);
        }
    }

Any help would be greatly appreciated :)

1 Comment
2024/05/02
08:51 UTC

1

I can not seem to be able to get the bars to generate normally, do you know why? I have issues binding the data-array to the objects

    //svg- Dimensionen
    var margin = {top: 50, right: 50, bottom: 50, left: 50},
    height = 600 - margin.top - margin.bottom,
    width = 600 - margin.right - margin.left;
    
    //Variablen
    counter = 0
    sum = 0
    text_counter = 0

    //Arrays
var countries = ['USA', 'China', 'Russia']
    orbits = ['LEO', 'MEO', 'GEO']
    data = []

    //Laden der Daten
d3.csv("satellites.csv").then(function(csvData)
{
    console.log(csvData);
        for(var ind = 0; ind < orbits.length; ind++)
        {
            for(var index = 0; index < csvData.length; index++)
            {
                if(csvData[index].ClassofOrbit == orbits[ind])
                {
                    counter++;
                }
            }
            sum = sum + counter;
            data.push(counter);
            counter = 0;
        }
        sum = 0;
    logData(data);
});

    //svg
var svg = d3.select("body").append("svg")
            .attr("height", height + margin.top + margin.bottom)
            .attr("width", width + margin.right + margin.left)
            .append("g")
            .attr("transform", "translate(" + margin.left + ", " + margin.top + ")");

    //Achsen
        //X-Achse;
var newCountries = copyArray(countries);
    newCountries.push("other");

var X = d3.scaleBand()
          .domain(orbits)
          .range([0, width])
          .paddingInner(0,1)
          .paddingOuter(0,1)
svg.append("g")
    .attr("transform", `translate(0, ${height})`)
   .call(d3.axisBottom(X))
        //Y-Achse
var Y = d3.scaleLinear()
          .domain([0, 7000])
          .range([height, 0])
svg.append("g")
   .call(d3.axisLeft(Y))

   //Balken
svg.selectAll(".Balken")
   .data(data)
   .enter()
   .append("rect")
    .attr("class", "Balken")
    .attr("x", function(d) { return X(d.orbits)})
    .attr("y", function (d) {return Y(d.data)})
    .attr("width", X.bandwidth())
    .attr("height", function (d) { return height - Y(d.data) })

    //Funktionen
function logData(data)
{
    console.log(data);
}

function copyArray(Arraytocopy)
{
    var newArray = []
    for(var index = 0; index < Arraytocopy.length; index++)
    {
        newArray[index] = Arraytocopy[index];
    }
    return newArray;
}
2 Comments
2024/04/30
12:45 UTC

1

What am I missing here? Trying to find min/max values

I'm currently teaching myself d3. I have a background in BI (SQL, python pbi, tableau etc.) but only have a basic understanding of javascript and web dev in general.

Can someone help me understand how to set variables based on aggregations of my dataset?
My dataset a simple csv file.

According to the d3 documentation, to get the max value of an array I can use d3.max(data, function to return column)

https://preview.redd.it/naeo3k33d5xc1.png?width=478&format=png&auto=webp&s=31d672ed2a2bea6d2c3b8f9817bab4895d03870f

However when I try this I end up with an errors saying that "t is not iterable"

This is my code. The dataURL is just my csv.

https://preview.redd.it/3tmrr7ucd5xc1.png?width=447&format=png&auto=webp&s=9e5ea428244db306090bdf5d4511290f120b0933

I'm assuming this is something to do with baseData returning a promise rather than an object however I'm not really sure how to handle this.

I've seen some examples of different applications using the ".then" function to work with promises so tried doing this

https://preview.redd.it/fbqnybj6e5xc1.png?width=528&format=png&auto=webp&s=ba7c29e6f3f79e54f1920c5e68edbd8e733f49ed

Sadly, this throws the same error.

I think I'm missing something about working with promises(?) or maybe I'm just doing something dumb lol

3 Comments
2024/04/28
04:32 UTC

5

Hello friends, I wanted to ask if anyone can recommend a decent guide to d3, I am new and it would help a lot, thanks in advance

0 Comments
2024/04/27
08:20 UTC

Back To Top