fabiochiu/medium-articles huggingface dataset:
Building D3 interactive network graph D3 Force-Simulation + React + TypeScript
By: Balram Chavan
Tags: React, Graph, Reactjs, Typescript, D3js

We can build very powerful network graphs using D3 Force Simulation library. I have already written how we can build such graph in Angular in my previous blog.

In this blog, I have done same exercise but with React.js and TypeScript. Before we start, checkout the running application to see what we are trying to build.

Let’s go!

Create new react application with TypeScript

npx create-react-app d3-network-graph-editor --template typescript

2. Add D3 package in application

yarn add d3

3. Add D3 types for IDE

yarn add d3 @types/d3

4. Run application to test everything is good so far.

yarn build

5. Let’s add code for our D3 network graph. First, we will create a SVG element reference and pass it to D3 for rendering graph and other class members for graph manipulation.

6. In constructor function we will initialise SVG reference.

7. The render() function would have a simple div with svgRef binding.

8. In componentDidMount() function, we will setup for our graph. We shall set size for SVG, setup a default nodes and links, force-simulation setup, drag feature setup, mouse pointers and mouse and keyboard event handlers etc.

9. Once setup is done, restart() method gets called which would be our starting point. This method redraws the graph by removing previous edges and nodes, adding new edges, showing drag lines, showing text for each node, setting an arrow direction etc.

10. These are the important functions in our code base. If you go through rest of the functions then you would find they are doing specific operations like tick() for calculating new line being drawn on drag, mousedown(), mouseup(), mousemove() for handling mouse events for adding new node, selection, drag etc and keydown() for handling keyboard shortcuts for changing arrow directions, deleting selected node etc.

11. Finally CSS, we would like to see a nice looking network graph, won’t we? In App.css, we would add these CSS classes.

12. Let’s test final output by saving all changes made so far and run yarn start if not running already. We should see a graph in action with default nodes and edges. We can add new node by mouse click, connect nodes by dragging them to target, move position of node by Ctrl + drag, change arrow direction of an edge by selecting it and pressing L or R keyboard button, delete node by pressing Del keyboard button etc.

13. You might have noticed that code is not very TypeScript friendly and lots of variables are of type any . In next iteration, I would refactor and try to use right D3 types rather but feel free to submit PR if you are faster than me :) !

14. You can find source code on my GitHub repository.

Cheers!
Simple D3 with React Hooks. React Function Components with Hooks…
By: Jeff Butsch
Tags: React, JavaScript, Hooks, Typescript, D3js

React Function Components with Hooks gives us a nice way to integrate D3 with React. There are many related articles that describe this already but they get in the weeds and complicated quickly. This article is just the basics on where to put things to get started correctly. You can expand from there.

In the past it was confusing to find the correct places to put D3 code, especially for someone new to D3 still getting their head wrapped around D3’s way of doing things. Optimization to minimize re-rendering was an advanced task when it should be easy.

Function Components with Hooks cleans this up quite a bit. There is one place to put D3, one way to connect it to React’s DOM, and re-render logic is mostly built in.

useRef Hook

We’re building a function not a class. There are no class member variables so we need a way to hold onto an object across multiple rendering passes.

useRef() creates a variable that does just that. The variable acts a lot like a class member variable without the class. We will utilize useRef() to hold onto the DOM element containing our D3 content. A ref is “get” and “set” via its .current property.

useEffect Hook

useEffect() gives us a place to put side effects such as our D3 code. Side effect?! It’s a side effect because it adds content to the DOM outside of React’s virtual DOM mechanism. (Note: useEffect() is like componentDidMount() and componentWillReceiveProps() combined, with change detection as a first-class feature.)

Here is a complete example Hooks and D3 (Typescript):

Here is what the example is doing:

Call useRef() to create a variable ( d3Container ) to hold the SVG element. Initialize it as null . React will set it the first time the page is rendered (because we tell it to on code line 60.)

Why not just use d3.select() to get the SVG element, or insert the SVG element using pure D3? By using a ref variable we can use it as a dependency in our useEffect() block to detect when the element has actually been rendered and available.

Call useEffect() to execute our D3 code. useEffect() takes two arguments — a function to run, and an array of dependency variables. useEffect() will run every time one of the dependency variables changes (a lot like computed properties in Ember and Vue if you’ve ever used those). Because we listed data as a dependency, useEffect() will run again whenever data changes. We don’t need to write code to compare old and new data for changes anymore!

The Function Component returns an SVG element, and its ref attribute is set to d3Container — the ref variable we declared at the top of the function.

React will run our D3 code when the DOM is ready and when the data changes.
I have to disagree -vehemently- with this article on several points.
By: Andrew Douglas Hope
Tags: Music Visualization, D3js, Data Driven

I have to disagree -vehemently- with this article on several points. I raise this particularly because it appears unwarrantedly high in Google’s search results.

My first and foremost issue is that (as your article brings all too clearly home) libraries such as React and Vue are essentially treating effects (resource limitations and related cosmetic issues), not their root causes. D3.js accepts these limitations, lives with them yet can, if required, work with React and Vue. Your article is effectively comparing apples with pears.

If d3.js is challenging, it is because of it’s remarkable scope, multi-DOM affinity and flexibility. None of these make it any less worthwhile learning. Indeed, it brings everything from base data to final visual expression together in one seamless flow.

You talk about scalability, but only in it’s most trivial form, namely screen resolutions. D3.js is data-driven, which allows parameterisation and reuse across the entire processing chain. This is the embodiment of scalable, or generative, freedom. One program potentially handles all conceivable permutations.

Why is this important? Increasing complexity will force developers towards generative (exhaustively comprehensive) systems — the yin to AI’s yang.

Any end device: with a data-driven core, presentation is a simple, JIT decision, based on end device characteristics and capabilities. To this end, d3.js can inter-work with any of ascii, canvas, SVG, and the libraries mentioned above. Bye-bye piecemeal, competitive programming. Hallo “program once for all time” — for all end device capabilities, past, present and future.

d3.js’s functional paradigm is extraordinarily elegant and compact. Your coding example may be easy to understand, but it is ugly, and -in a scaleability sense- severely hamstrung.

d3.js is well-suited to handling multi-channel, streaming data in all it’s complexity. At present we are in an IoT stone age. This will change. Data will with time be united in fine-grained, MusicXML-style parallel, time-synchronised streams. Selectable, storeable, replayable, shareable.

Moreover, d3.js supports the free mixing and matching of heirarchical classification trees, which accommodates very natural domain visualization extension.

Examples? Music (audio or notation) to visual theory tools, instrument visualisations, underlying physics simulations, to psychophics (colour/emotion etc) visualizations — and much more.

A further advantage of d3.js is that with CSS ids and classes shared between clients (and given near-real-time communication), we will see an explosion of web-based collaborative systems bringing together AI and conventional programming to support interactive design, all while leveraging human’s wildly imaginative associative skills.

This is the d3.js near future. Beyond that? 3D data-driven systems to replace data-impoverished WebGL systems. These will adopt d3.js as a role model.
How to build sliders with d3.js
By: Karen Mcclellan
Tags: Prototyping, Programming, JavaScript, D3js, Tutorial

Set up your work space.

Set up your files in a directory:

index.html

main.js

main.css

Install d3.js

Download d3.js and unzip to your project folder, or alternatively you can link to the script at the bottom of your html file:

<script src="https://d3js.org/d3.v5.min.js"></script>

Install d3-simple-slider via Terminal with npm install d3-simple-slider or you can download from GitHub.

Set up your HTML & CSS

I’ll leave the CSS up to you, but here’s a basic setup for index.html with 2 div elements we’ll end up calling on in our main.js file.

The first, id="mood" , contains an SVG, which is what we’ll manipulate with the sliders. (I generated the SVG using Blobmaker) The second, id="slider-color-picker" , is empty for now. The JavaScript will do the work of building out the slider.

Set up main.js.

Let’s walk through the script. First, we set variables for the SVG and the colorSlider div we set up in index.html

Next, we write a function that will convert RGB values to hex:

Then we select the div we named in index.html and append an SVG that essential acts as a canvas for the 3 RGB sliders we’ll call in a minute.

Next, we name the function that calls and styles the sliders for each of R, G, and B. (For different styles of sliders, check out John Walley’s tutorial.) This script also changes the color of the blob to the rgb values chosen on the sliders. Finally, you invoke the slider canvas and call the slider function.

Test it out and tweak as needed

You should have a working blob and rgb slider set now. Play around with it and make changes as needed!
Visual representation of the Fibonacci sequence
By: Arnaldo Gunzi
Tags: Vba, Visual Math, Forgotten Math, Fibonacci, D3js

The Fibonacci sequence has been fascinating mathematicians since immemorial times: a simple formation with many amazing properties.

This sequence begins with 1 and 1. The other numbers are the sum of the previous two. Hence, the following numbers are:

1 + 1 = 2

3 = 1 + 2

5 = 3 + 2

8 + 5 = 3

and so on.

There is a beautiful way to view this sequence.

Starting with a square of side 1, place another identical square on your side.

The next number is the sum of these two.

And so on.

1, 1, 2, 3, 5, 8, 13, 21, etc …

With 10 squares:

I created two little programs to plot this view.

A Javascript D3, which is a fantastic library for graphics. See interactive project on Github here: https://asgunzi.github.io/Fibonacci/

And another in Excel — VBA, available for download here . Screen print:

VBA is underestimated these days, but it is a language as powerful as all others.

The essence of both plots is not very difficult. In VBA, the command to add a rectangle is as follows.

ActiveSheet.Shapes.AddShape (msoShapeRectangle, x0, y0, side by side) .select

Simply enter the starting position (x, y) and the size of the side.

Then color the interior and the edge.

With Selection

.ShapeRange(1).Fill.ForeColor.RGB = Information.RGB(200 * Rnd, 200 * Rnd, 200 * Rnd)

.ShapeRange(1).Line.ForeColor.RGB = Information.RGB(0, 0, 0)

.ShapeRange(1).Line.Weight = 1

End With

The inspiration for this little project was the cover of the book “Number Theory”, George Andrews.
Add interactivity to your charts in Angular apps with d3.js
By: Adrien Miquel
Tags: Data Visualization, Web Development, JavaScript, D3js, Angular

As you may understand, we update the svg dimension, then the chart config (arcs for pie/donut, axis scales for bars) and finally, we repaint all the chart which means slices for pie/donut or bars and axis for bar chart.

Interactivity

It may be interesting to add some cool stuff like a tooltip which will follow the mouse move. Or if you prefer some labels near your bars or slices. Let’s put some dynamism with transitions (ease functions and delay) too.

Tooltip

Adding a tooltip requires few changes. First add, a CSS rule to component:

styles: [

`div.tooltip {

position: absolute;

text-align: center;

width: 80px;

height: 40px;

padding: 5px;

font: 12px sans-serif;

background: black;

color: white;

border: 0px;

border-radius: 8px;

pointer-events: none;

vertical-align: middle;

z-index: 10;

}`

]

You can notice the mousemove callback argument data structure changes between pie and bar charts. This comes from the the data we provide :

this.slices.data(this.pie(this.dataSource)); // For pie chart

this.bars.data(this.dataSource); // For bar chart

A smooth tooltip yeah!

Labels

Bar chart

Here is the corresponding CSS rule for labels:

svg text.label {

fill: black;

font: 15px;

font-weight: 400;

text-anchor: middle;

}

The code to adapt

Pie chart

For the pie chart, we are going to display the name on each slice above 5%, and values on the ones over 25%. Here is the code:

Donut chart

Don’t forget to update the code to transform your pie to donut chart:

private setArcs() {

const thickness = .75; // Or any value you want

this.arc = d3.arc()

.outerRadius(this.radius)

.innerRadius(this.radius * thickness);

}

Then, specify label properties for the total and hovered item.

It renders this:

Of course, I could have used css classes but I prefered managing styles programmatically to avoid numerous files.

Transitions (animations)

The transitions in d3.js are quite easy to manage.

3 methods to apply on d3 objects like bars or slices add some dynamism to your chart.

this.bars

.transition()

.ease(d3.easeBounce) // or any other ease function (optional)

.duration(150)
Creating a Line Chart with React-Vis
By: Kaeland Chatman
Tags: Charts, React, JavaScript, React Vis, D3js

React-Vis is an incredibly configurable charting library open sourced from the folks at Uber. It’s main premise is that it provides D3 functionality while still using React component and props. This is great given the fact that React is a widely popular view framework used by many frontend developers. D3, on its own however, has a bit of learning curve. Let’s see how quickly we can spin up a line chart with React-Vis. Ok, let’s start.

Much like in middle school algebra, React-Vis line charts are composed of a familiar set of components, namely: horizontal and vertical grid lines, an x-axis, a y-axis, and the actual line to be drawn on the chart. To compose a line chart, we’ll first need to import the wrapper component for our chart from the react-vis library in addition to the css styling. This component looks like the following:

import ‘../node_modules/react-vis/dist/style.css’; // css styling from the react-vis node module <XYPlot height={400} width={400} />

Please note, this component must be passed both height and width props. Having imported our wrapper component, we can now import the gridlines, as well as our x & y axes. They look like this:

<VerticalGridLines /> <HorizontalGridLines /> <XAxis /> <YAxis />

Simple enough right? Now let’s create our chart with it’s corresponding grid:

<XYPlot height={400} width={400}> <VerticalGridLines /> <HorizontalGridLines /> </XYPlot>

Ok sweet! Now, in order to display a line on this chart, we’ll need to import our final component, called a LineSeries.

<LineSeries />

This component will take a single property called data, which will be passed an array of objects with x & y properties.

const data = [{x: 0, y: 8}, {x: 1, y: 5}, {x: 2, y: 4}] <LineSeries data={data} />

With this, we can now finalize our React-Vis line chart by adding in our <LineSeries> component like so:
Exploring Recharts: Reference Area
By: Gaurav Gupta
Tags: React, JavaScript, D3js, Charts, Recharts

A reference area or highlighted area in a chart, as the name suggests, can be used to highlight some important information in the chart. This can, for example, be used to mark a period of decline in sales of a commodity, and provide extra context on hover or other interactions.

Recharts provides an implementation of ReferenceArea which has a fairly easy API and also a fairly convenient customization API using the shape prop.

A basic example:

Also note that:

if you only specify x1; x2 would be extrapolated to the end of domain

if you only specify x2; x1 would be extrapolated to the start of the domain

if you only specify y1; y2 would be extrapolated to the end of range

if you only specify y2; y1 would be extrapolated to the start of the range

The label for this ReferenceArea can be customized as any other custom label in Recharts.

But wait!, Recharts also exposes a shape prop for the ReferenceArea , which can be used to provide a custom shape to the ReferenceArea as opposed to the default rectangle. Recharts passes on all the required props to this shape function to do any kind of customizations you require.

Check out this example, which renders a circle . Do remember that this shape should return an svg element, so that it can be rendered inside an svg . This also means you can use the foreignobject “hack” to work around this.

That’s not it. Check out this example with interactions. We are showing/hiding another svg element on hover over the ReferenceArea

A list of all other posts in this series:
Marvel vs DC movies: Is DC really that far behind ?
By: Saurabh Dhiman
Tags: Visualization, Dc, D3js, Marvel

Blockbuster superhero movies are increasingly dominating the movie release calendar each year. While Marvel is clearly leading the way with an ever growing fan base, how far behind is DC ?

While box office is the most talked about measure of success, profits earned and ratings from critics will also have an influence on the long-term legacy of these movies. Let’s take a look at how the two studios compare.

Marvel has delivered at scale

The studio has benefited from having a clear vision of how they wanted to evolve their cinematic universe, while DC seemed to be just reacting to what Marvel was throwing at them. Since 2000, Marvel movies have generated over 3 times more revenue from ticket sales worldwide.

Movies released since 2000

However, if we look at box-office per movie, DC is not too far behind (around $500M per movie compared to $687M for Marvel).

Low movie ratings not a hindrance to commercial success

While Marvel has clearly been a big hit with the movie critics, movies panned by critics across both studios have succeeded as well.

Rotten tomatoes classifies ratings > 60% as ‘Fresh’ & rest as ‘Rotten’

DC’s “Suicide Squad” ($746M box-office and 27% rotten rating) and “Batman v Superman: Dawn of Justice” ($873M box-office and 28% rotten rating) demonstrate the strength of the studio’s fan base.

The interactive tool here gives a deep-dive into all Marvel & DC movies released since 2000 (Desktop & tablet friendly as of now). Demo below:

DC is starting to find it’s feet

In the last couple of years, DC has tweaked it’s strategy and focused on single characters rather than trying to put together an ensemble like Marvel. And it is starting to work, with both “Aquaman” (2018) and “Joker” (2019) entering the $1B club that Marvel clearly dominated.

Big returns on a low budget is the new breed of blockbuster

While most Marvel & DC productions have budgets over $150M owing to the extensive VFX action sequences, Deadpool changed the game by creating a new sub-genre that got an overwhelming response. An R-rated film with a $58M budget produced amazing returns($783M in worldwide box-office) for 20th Century Fox (since acquired by Disney and part of MCU).

Joker did something similar for DC in 2019. With a production budget of $55M, Joker passed Deadpool as the highest grossing R-rated film of all time. These successes have now opened up the path for more variety in the genre that can be highly profitable if executed well.
D3.js 資料視覺化工具(上)
By: Jacy Chu
Tags: JavaScript, D3js, Frontend

D3 基本用法

開始學習前，先引用好 d3 library，並在 js 檔案中輸入 console.log(d3)

點擊瀏覽器開發者工具，查看一下：

d3 (object) helper methods

上方密密麻麻都是 d3 object 內建提供的 helper methods！

✨ D3 — 選擇 ( D3 Selection )

把 D3 library 引用到 HTML 頁面中，即定義了一個全局 JavaScript 對象 d3。而操作之前，需要先做選擇動作。

d3.select('css-selector')

根據指定的 css-selector 返回 HTML 文檔中第一個匹配的元素

d3.selectAll('css-selector')

根據指定的 css-selector 返回 HTML 文檔中所有匹配的元素

有關 css-selector 可以是節點、id、class…等，詳細可以參閱說明 🔍

✨ D3 — DOM 操作( DOM Manipulation )

先做了選擇動作後，接著要操作，以下為常見的操作方法：

text('content')

獲取或設置被選元素的文本

append('element name')

在所選元素內，但在所選元素的末尾之前添加一個元素

insert('element name')

在被選元素中插入一個新元素

🔖 補充說明

1.insert可以指定將新元素插入在什麼位置，而append只能將元素添加在末尾!

2.append()&insert()只是新增空的標籤而已, 必須再呼叫text()或html()加入內容才看得到。

remove()

從 DOM 中移除指定的元素

html('content')

獲取或設置被選元素的內部 HTML

attr('name','value')

獲取或設置所選元素的屬性

property('name','value')

獲取或設置所選元素的屬性

style('name','value')

獲取或設置被選元素的樣式

classed('css class',bool)

從選擇中獲取、添加或刪除一個 css class

✨ D3 — 方法鏈 ( Method Chaining )

D3 提供方法鏈，將第一個方法的輸出作為輸入，傳遞給鏈中的下一個方法。原始寫法舉例如下：

var bodyElement = d3.select("body"); var paragraph = bodyElement.append("p"); paragraph.text("Hello D3!");

可以使用方法鏈簡化寫成：

d3.select("body").append("p").text("Hello D3!");

✨ D3 — 資料函式 ( Function of Data )

前面提到的 DOM 操作，函數可以接受值或函式作為參數。以函式作為參數稱會是匿名函式形式。以 text() 作為範例如下：

.text(function(d) {

return d;

});

除了代入參數，也提供 index：

.text(function (d, i) {

console.log(d); // the data element

console.log(i); // the index element

console.log(this); // the current DOM object

return d;

});

延伸運用也提供了動態屬性，舉例如下：

<p>Error: This is error.</p>

<p>Warning:This is warning.</p> <script>

d3.selectAll("p").style("color", function(d, i) {

var text = this.innerText;



if (text.indexOf("Error") >= 0) {

return "red";

} else if (text.indexOf("Warning") >= 0) {

return "yellow";

}

});

</script>

✨ D3 — 事件處理 ( Event Handling )

on() 方法為所有選定的 DOM 元素添加一個事件偵聽器。第一個參數是事件類型，第二個參數是事件發生時執行的回調函數，並可以指定第三個可選參數捕獲標誌。語法如下：( Type 是事件名稱，listener 是事件監聽器)

d3.selection.on(type[, listener[, capture]]);

selection.on()

添加或刪除事件偵聽器以捕獲事件類型，如單擊、鼠標懸停、鼠標移出等

selection.dispatch()

捕獲事件類型，如 click、mouseover、mouseout

d3.event

事件對象，用於訪問標準事件字段，例如時間戳或 preventDefault 等方法

d3.mouse(container)

獲取指定 DOM 元素中當前鼠標位置的 x 和 y 坐標

d3.touch()

獲取容器的觸摸坐標

詳細可以參閱說明 🔍

✨ D3 — 動畫 ( Animation )

selection.transition() 為所選元素安排轉換

transition.duration()

指定每個元素的動畫持續時間(以毫秒為單位)

transition.ease()

緩動指定緩動函數，如：linear、elastic、bounce
How to create D3 v6 calendar heat map
By: Petr Jahoda
Tags: JavaScript, D3js, Calendar, Tutorial, Go

How to create D3js v6 calendar heat map

D3js is a Javascript library for doing graphical magic on data. In the year 2020, it was upgraded to version 6.

And this brings us a little problem. Official examples gallery doesn’t use Javascript, instead it uses special Observable Notebook language. It is not easy, nowadays, to find an up-to-date version 6 examples of D3js charts.

This was the reason for this article. I was not able to find out working example of version 6 calendar heat map so I decided to make one.

Please note, that this work stands on shoulder of other people.

In this article, we will use strategy I learnt in Amelia Wattenberger’s book and we will build on those steps:

Access the data Create chart dimensions and scales Draw the canvas Draw data Set up interactions Draw peripherals

We will use latest version of D3js, which is version 6.3.1, as of January 9, 2021. We will use Go as a web server to simulate some pseudo-real world backend data sending. And we will use Goland as an IDE.

You can skip Preparing the project, if you only need the D3js information. As always, you’ll find link to Github repository at the end of the article.

Here you can find more information about creating web server in Go.
Using ObservableHQ in JavaScript with your own data.
By: Daniel Ellis
Tags: Observablehq, Towards Data Science, JavaScript, Visualization, D3js

Supplying new data to the plot

As it stands, the data used for the plot has been uploaded to the ObservableHQ servers. Instead, we may wish to use our own data within the visualisation. In the following example, we have download the airports.csv file locally (see the points cell for the URL) and will read it in and edit it before updating the chart output.

For simplicity, we use the Data Driven Documents (d3) library to read the CSV fiel.

This is already used within the notebook, and therefore can be extracted within the Runtime segment of the code. Alternatively, it can be imported with the following script:

<script src="https://d3js.org/d3.v6.min.js"></script>

We are now able to load the file and update the points cell of the notebook. To do this we define a ‘parse’ function to process the data read from a CSV.

To distinguish between datasets, we also add a random component to the longitude and take 70% of the latitude values before pushing the processed data into points using the main.redefine function.

function parsedata(data){ //convert to numerical and add randomness

data = data.map(({ longitude, latitude })=>

[+longitude+Math.random(), +latitude*.7])



// update points cell

main.redefine("points", data );

}

And as with any good code we actually need to run it. This can be done with:

d3.csv("./airports.csv").then(parsedata)

Edited / custom cell values and data

https://wolfiex.github.io/ObservableTutorial/local_data.html
Building Time-lapse Visualizations with React Hooks and D3 (part 1)
By: John Bellizzi
Tags: Data Visualization, React Hook, D3js, Visualization Transitions

Note: This is part 1 in a 3-part series. The second part of this tutorial can be found here, and part 3 can be found here.

Interactive transitions in our visualizations add context to changing elements across different data states (see Mike Bostock’s article on object constancy). This can be especially powerful for changing events that occur in geographic space. Above, we have an example of a visualization we are working on that demonstrates the growth of COVID-19 cases over time across the US. The timeline at the top automatically plays through a daily series of events, and can be clicked to act as a selection filter.

The charts are built using React Hooks to control the time functionality, and D3 to plot the line and map. In this article (part 1 of the series) we are going to go over how the timer hook is built, and how we can use it to display time and control play state. Later pieces in this series will show how we use the time along with data to plot cases on the map, as well as adding more control to the timer.

With React Hooks, we can compose hooks together to create our own custom hooks that internally keep and update state. Our timer hook initializes with a start and end date, a step period, and an update frequency. What we get back is the current time state, and functions that allow us to play, stop, and update the time.

Our custom hook takes in the following properties

startTime: Minimum time of timer

endTime: Maximum time of timer

step: Number of milliseconds the timer increases by on each tick. If we want our timer to increase by 1 day every tick, we will set our step to be 1 day * 24 hrs/day * 60 mins/hr * 60 secs/min * 1000 ms/sec = 86400000 ms

frequency: How many times per second the timer increases by the provided tick. A value of 1 with the above step will increase the timer value by 1 (86400000 ms) every second

From this, we get the current state of the timer that can be displayed, and functions that allow us to control the timer.

We can decrease our step to 60 * 60 * 1000 = 3600000 so that every tick increments the timer by 1 hour instead of 1 day

This is a pretty slow update though, so let’s see what happens when we also increase our frequency to 24 ticks per second
To d3 or not d3 in React
By: Cynthia Eddy
Tags: JavaScript, D3js, React

my logo

While building my portfolio to showcase my projects, I wanted to animate my logo so it would swirl, like an eddy. My first thought was to have it roll from right to left, and then stop to where it would always live on the page.

Then I thought maybe it would bounce upon load — just a simple animation.

I built out the home page with a svg circle first using d3 animation by the documentation found here.

I tinkered with the code until I had it playing exactly as i wanted: speed, size and x coordinate.

As I continued to build my app, the design morphed into having a home page where the circle would bounce a few times, then disappear below to land on all the other pages with the same x coordinate.

I had already built out the pages with my logo being stationary unless you hover over it, then it rotates once. That was another journey, albeit a much shorter one — it ended successfully.

home page

Since I could fill the circle with color using CSS, i thought placing my jpeg logo would be as easy as giving the circle a background image. That didn’t work. Then I tried saving my logo as an svg in photoshop, but couldn’t save the shape as a circle, only a square. So now my quandary is how to you place an image in a circle svg that’s built in react?

I’ve spent hours looking up documentation and as of yet I haven’t come up with a solution. Since I have my animation working the way I want, I’ll spend more time trying to figure it out. It doesn’t make sense to have a transparent black circle bouncing on my home page unless my logo is living inside it, and my tenacity almost always wins out, for better or worse.

So, my next step is to do more research, and may have to forgo d3 and come up with another solution. Once I’ve figured it out, I’ll post my outcome.

Thanks to Swizec Teller
D3 Multi Line Plot from a CSV
Tags: JavaScript, D3js

Figure 1: A multiline chart created with D3

Line graphs are one of the oldest and simplest visualizations. Draw a dot at every data point and connect them. Despite the ease of creation on paper, line graphs are tricky to implement with D3. I started learning D3 with scatter plots and bar charts. Those visualizations expect each data point to be represented by a row in a CSV file. However, to draw a line, D3 uses the SVG path element which is one continuous path derived from an array of coordinate pairs. In this case, each row of the CSV would have to contain every data point associated with a line which is unwieldy. This is where the D3 Nest function comes in handy. It takes in a vertically oriented dataset and groups it by key.

Let’s say I want to plot the number of tropical depressions, tropical storms, and hurricanes in the Atlantic ocean each year. I only need 3 data columns. The year signifies where on the x-axis the data point will appear. The severity is the key which maps the data point to a line. The count is the y-axis complement to the year. This vertical organization pattern is more efficient for a computer to process and follows the Tidy Data principles.

Figure 2: Input and output format of d3.nest()

Before I plot the line graph, I want to explain the result of invoking D3 Nest. The function returns a JSON object that has keys of type String for each storm severity. Each corresponding value is an Array of Arrays. The inner arrays each contain an entire row of data from the CSV file. D3 will traverse the Array of Arrays and use the data within to draw the path.

Creating a multi line plot is remarkably similar to a single line plot once the data has been organized. Instead of providing data for a single line, I simply pass the entire nested data object to the line generator as shown in the below code excerpt. The line generator draws a line for each key in the nest; they are separate SVG objects that can be interacted with individually.

lines.selectAll(".line")

.data(nestedData)

.enter()

.append("path")

.attr("class", "line")

.attr("d", function(d,i) {

return lineGenerator(d.values);

})

.style("fill","none")

.style("stroke", function(d,i) {

return colors[i];

})

.style("opacity", .9)

.style("stroke-width",4);

In the end, the data refuted my belief that the number of hurricanes per year has increased over time and that’s ok! I continued working on the visualization and added labels and formatted the axis ticks. Check out my gist if you are interested in seeing the source code.

Original publication
Integrating D3.js to a Typescript React Application
By: Krasnoff Kobi
Tags: Typescript, D3js, Typescript With React, React

In today's front-end application development, the ReactJS library has become the most popular Javascript/Typescript framework.

On the other hand, D3.js is the most commonly used Javascript library for creating dynamic charts on the Web.

Integrating the two frameworks and more than that using the Typescript language can be a bit tricky. But it is absolutely possible. That is the purpose of this article.

Create and install the libraries

First of all, we will have to create a new react project. If we choose the Typescript language then it is recommended to define a Typescript template. This is done by the following NPM command:

npx create-react-app react-ts-chart — template typescript

The next step is not mandatory but it is recommended if you want to use Sass precompiler for your project:

npm install node-sass — save

Now, Let import the D3.js library. The first line is the D3.js files and the second line is for the Typescript definitions:

npm i d3 npm i @types/d3

That will be enough for creating our first graph.

Creating our first page

Let's create our first page containing our first graph. A basic Typescript template will look something like this:

D3 Principles

D3 is a javascript framework that illustrates its graphs on an SVG element. So we will have to define such an element. First, let’s define an SVGSVGElement object:

ref!: SVGSVGElement;

and link it to an SVG element:

<svg className=”container” ref={(ref: SVGSVGElement) => this.ref = ref} width=’100' height=’100'></svg>

now let’s import the D3.js library to our component:

import * as d3 from ‘d3’;

For this tutorial, we will implement a very simple bar graph, the data will be a simple hardcoded Number array. Let’s build a private function that illustrates the graph:

In a React component, there are several life cycle stages. One of them the componentDidMount() function. This stage executes after the constructor and the render (in this stage you actually draw the HTML) stages. So let’s execute the buildGraph function on the stage.

The final component should look something like this:

Now let’s design our new graph by an SCSS template:

Our new graph should look something like this:

Conclusion:

Congratulations! we have made our first step toward implementing graphs and charts to our react applications.

The full source code can be found at: https://github.com/krasnoff/react-ts-chart
Easier D3.js — Render C3 Charts With React Functional Components
By: Jennifer Fu
Tags: C3, React, Programming, D3js, Charts

Static C3 Charts

We will use the Create React App as a starting point. Since C3 is a wrapper of D3, both c3 and d3 packages are needed.

npm i c3

npm i d3

Then the following packages become part of dependencies in package.json .

"dependencies": {

"c3": "^0.7.20",

"d3": "^5.16.0",

}

Change src/index.css to this for minimal styling:

C3 generates a chart by calling generate() with a config object. The chart will be inserted into the element specified by the bindto selector in the config object.

We create src/Chart.js where the official C3 example is rendered by a React component:

In the above code, the functional component, Chart , generates an element, <div id=”chart” /> (line 18).

The config object for the generate API is defined in lines 6-15. Line 7 instructs to insert the chart into the element whose id is chart . Lines 9-12 hardcode two data series: data1 and data2 . Line 13 defines the chart type to be line . Lines 5-16 generate the C3 chart in useEffect . This chart will not be updated since the dependency list is an empty array (line 16).

In src/App.js , we invoke this chart component in line 5:

Run npm start , and we see the following chart:

What happened? This chart has no styles. The C3 styles need to be included in src/Chart.js or src/App.js (line 3).

With styles, the chart looks the same as it does in the official C3 document.

Source: Video provided by the author via Youtube

You can hover over the lines to view data in detail. Each line can be showed or hidden by hovering or clicking the data series name on the x-axis.
Concept Visualization for solving Wumpus World Problem
By: Anisha Swain
Tags: Visualization, Algorithms, D3js, JavaScript

Have you ever seen an automated vacuum cleaner cleaning the house? It cleans the whole room without any human interaction. But how does it get to differentiate between the position furniture and free space? Humans can do it easily by their vision and reasoning but for robots, it is pretty hard to get background knowledge about the environment. In AI, this approach is embodied in Knowledge-Based Agents.

Let’s play a game which will help you to clearly understand this concept. Here you will explore a new environment in order to win the heap of gold.

The game consists of an environment of 4X4 grids. It is called the Wumpus World. There will be a heap of gold which needs to be grabbed to win the game along with a wumpus lurking somewhere in the grids(fortunately the wumpus does not move). There will also be some bottomless pits here which can trap anyone except the wumpus. Now, go through the Game Rules and try to win the heap of gold.

Percepts:

When you will be near a wall, you will get a bump percept.

When there will be a wumpus nearby, you will get a stinct percept

When there will be pits nearby, you will get a breeze percept

When you will be near a wall, you will get bump a percept.

If you get stuck in a grid with the wumpus, you will get a scream percept

Note: Hereby “nearby”, we mean the adjacent cells(Excluding Diagonal) of your position

Well, were you able to grab the gold coins? Yes? Pretty simple isn’t it? But will you be able to grab the gold if the wumpus, pits and heap of gold are hidden? Come on, give it try.

So were you able to win the game this time? Yes? But how did you do that? In the game, you acted as a knowledge-based agent, who initially did not have much background knowledge about the environment, as all the pits, wumpus and gold were hidden and you only knew about their presence, not location. You took the percept as input, combined and recombined information and yielded the Agent’s movement as output.

A Logical agent who will do the same thing:(TO DO)

Now imagine an automated robot playing the same game that you played earlier. Here the robot will act as the agent and it will start from [1,1] and try to go to cells which it knows does not have any pit or wumpus. Initially, its knowledge will contain the rules of the environment only and discovering the location of pits and wumpus will complete its background knowledge. In a typical situation where there is no clue about the environment, this type of knowledge-based agents works effectively to searching purpose.
Dress Like A Rah
By: Dress Like A Rah
Tags: Weight Loss, Body Image, Body Positive, LGBTQ

We have a problem that I want to talk about. We aren’t giving ourselves the space we need to liberate ourselves.

I know the big word liberation can be confusing. I always thought it was a word that didn’t apply to me and was for people who were bound to such deeper concepts than I could ever be. For example, I thought it only applied to women born in countries who are held captive and never allowed to make a decision for their own bodies. I thought liberation wasn’t a word that could be apart of my story.

I’ve come out of the closet, I cut off my hair, I fell in love, I shortened my name and I think I found pure happiness. I thought this was it. I didn’t know anything else needed to be liberated.

I’m writing this today because I figured out that I was totally wrong. I have work to do. I have to dig deep into the archives from which I was raised to let my body be whatever size it needs to be, to hug my curves the way they are and to let myself eat when I need to eat.

But I’ve worked too hard to be the best Rah I can be and no one is taking that away from me. No one is telling my LGBTQ fam how to be happy.

Someone, probably a man, somewhere sitting in a conference room for a big magazine a few decades ago decided what the perfect woman looked like. And they sold that idea to America. In fact — they created an entire industry for it. The diet industry.

I’m liberating myself from that concept, this terrible industry of lies and suffocation, this idea that I’m only strong if I eat certain calorie amounts per day or that I’m not woman enough if I wear a tie and I’m not man enough for not liking football. I’m liberating myself from the whispers of weight loss behind my back in church and the idea that I am better if I am woman enough.

Goodbye lies. Goodbye self torture. Goodbye gender norms.

Hello life without the fog.

I am strong because I am my truest self. I am strong because I woke up and decided I would look damn fine if I wore a jumpsuit. I am strong because I am telling my truth to the world.

I am strong because I am Rah.

I can eat dessert first, I can make pancakes whenever I want and I can keep that backup pizza in my freezer. No one is defining how I feel about my body and no one is deciding for me how queer I get to be.

Accepting that you’re not one gender, but rather a blend of both is liberation for me. Is it sometimes confusing and frustrating in department stores? Sure it is. But it means I get to rewrite the narrative and decide for myself what beauty is.

Body liberation: taking back the definitions that were pushed upon you and realizing that you can re-write your narrative.

It’s messy. It’s deep. It’s complicated. It’s the best damn thing that ever happened to me.
Letter to My Body
By: Danielle Thys
Tags: Body Image, Body Positive, Women

March, 20, 2021

Dear Body,

My one and only, much maligned, abused, and abandoned body, I will not start off with my usual opening line; the mantra of relentlessly polite women attempting to make nice in a world that would just as soon see them dead. A mantra of negation, concealment, hesitance, embarrassment, and excuse: I’m sorry. I’m sorry. I’m sorry. I’m sorry. I’m sorry.

I won’t subject you to that. We’ve had enough shame, haven’t we?

Nor will I say I love you. I do, in my stunted way. But we both know our relationship has been fraught and overwrought. I have betrayed you as many times as you have betrayed me. So I will not lie. You can always spot a bullshitter faster than I can anyway.

I will simply say that I see you and am grateful you have kept such a complete record of our history. I have learned over time to see that compilation of evidence with less judgment and know that what you’ve held for me has been held with purpose.

So…Thank you.

D.

__________________________________________________________________

March 21, 2121

Hey D,

Shut up and dance

🤪
My Big Reveal
By: Odelia Shargian
Tags: Intuitive Eating, Body Liberation, Body Positive, Eating Disorders, Body Acceptance

When I was 13 I experienced the onset of an eating disorder that has greatly affected my life and continues to affect it to this day. As much as I thought that I had it under control, it has only been recently that I realized how much of my behavior around food and my body is still skewed by my early struggle.

In an attempt to reach full recovery, I’ve made a principled decision that I’m not going to restrict my eating or intentionally try to play with my weight anymore and this has forced me to deal with my feelings about a body that is very different from what I’ve been trained to want and like. All of this has taken me on a ride to educate and support myself on how to eat more intuitively and how to accept my current shape.

To my surprise, I found that I’m not alone in this struggle and that there’s a whole community of people who are dedicated to thinking, researching and advocating around these issues. ThIs social movement of Body Liberation is totally radical, in the most positive sense of the word.

I can’t tell you how grateful I am that my journey has unfolded in such a way that I am able to offer Shake Your Soul® as a place of radical acceptance for Every Body to experience compassionate and joyful movement for the sake of simply feeling good in our bodies. Whether you struggle with body image issues or not, you’re welcome to join me and my beautiful community by clicking here: movementbliss.com/book

If you feel like you are struggling in a similar way and want to share anything about your personal journey, please feel free to make a comment below or write to me personally. I’d love to hear your thoughts, feelings and comments.
How to do Body Paint at Home like a Pro?
Tags: Painting, Body Painting, Body Painting At Home, Body Positive, Body Paint

How to do Body Paint at Home like a Pro? TechyFrogs Apr 13·1 min read

Getting stylish body paint on the body is a dream for some peoples. We watch movies and get inspired by stunning-looking body paintings on actor’s bodies. But getting beautiful rich looking body painting is expensive in the market and you end up paying hundreds of dollars for it.

Now you get to learn how to do body paint at home like a pro. It is easy and fun.

To get your dream body painting design, you should just follow 3 important steps:

Skin preparation for body painting Applying body paint at body Removing body paint

Body paint at home | Credit: Createlet

Proper Skin Preparation

Before applying the paint to the skin, it is recommended that you take a shower and wash it thoroughly. In short, take a shower before body painting — if you want the results to look good.

A good wash will remove these oils and allow the paint to latch in a very easy way.

This step is important if you have oily skin on your face (especially the T-zone), as it will be harder to maintain the appearance of the paint.