D3.js cant display a tooltip - reactjs

I'm trying to add a tooltip each time when hovering circles in my line chart.
As you can see in the picture below tooltip is exist in dom but I can't display it. Here I recreated my problem in sandbox:
https://codesandbox.io/s/serene-browser-t38ud6?file=/src/App.js
const tooltip = d3
.select(d3Chart.current)
.append("div")
.attr("class", "tooltip")
.style("opacity", "0")
.style("background-color", "red")
.html(`<p>test</p>`);
const mouseover = function (d) {
console.log("tooltip");
tooltip.transition().duration(200).style("opacity", 0.9);
};
svg
.append('g')
.selectAll('dot')
.data(data)
.enter()
.append('circle')
.attr('cx', function (d) {
return x(d.date);
})
.attr('cy', function (d) {
return y(d.balance);
})
.attr('r', 5)
.attr('fill', '#69b3a2')
.on('mouseover', mouseover);

I followed this article, and you just need to move the div outside the svg
create a ref to select the tooltip div
const tooltipRef = useRef();
add it to the HTML
...
</button>
<div className="tooltip" ref={tooltipRef} />
<svg id="chart" ref={d3Chart}></svg>
...
And change its style on the mouse events
const mouseover = function (event, d) {
console.log(d);
const tooltipDiv = tooltipRef.current;
if (tooltipDiv) {
d3.select(tooltipDiv).transition().duration(200).style("opacity", 0.9);
d3.select(tooltipDiv)
.html(d.balance)
// TODO: some logic when the tooltip could go out from container
.style("left", event.pageX + "px")
.style("top", event.pageY - 28 + "px");
}
};
const mouseout = () => {
const tooltipDiv = tooltipRef.current;
if (tooltipDiv) {
d3.select(tooltipDiv).transition().duration(500).style("opacity", 0);
}
};
...
.attr("fill", "#69b3a2")
.on("mouseover", mouseover)
.on("mouseout", mouseout);
https://codesandbox.io/s/youthful-cloud-tsu6sj?file=/src/App.js
Notice there are some styles for the tooltip in styles.css

Related

Create static network graph with D3 in react

I want to generate a static network graph, where the nodes only update the radio atributte and the links changes via props.
const NetworkGraph = props => {
const areaChart = useRef()
const dimensions = {width:400, height:200}
useEffect(() => {
const svg = d3.select(areaChart.current)
.attr('width', dimensions.width)
.attr('height', dimensions.height)
.style('background-color','white')
const nodo = svg
.selectAll("circle")
.data(props.data)
.enter()
.append("circle")
.attr("r", d => d.valor /* Math.floor((Math.random() * 40) + 1) */ )
.style("fill", "#69b3a2")
const link = svg
.selectAll("line")
.data(props.links)
.enter()
.append("line")
.style("stroke", "#aaa")
var simulation = d3.forceSimulation(data.nodes) // Force algorithm is applied to data.nodes
.force("link", d3.forceLink() // This force provides links between nodes
.id(function(d) { return d.id; }) // This provide the id of a node
.links(data.links) // and this the list of links
)
.force("charge", d3.forceManyBody().strength(-500)) // This adds repulsion between nodes. Play with the -400 for the repulsion strength
.force("center", d3.forceCenter(dimensions.width / 2, dimensions.height / 2)) // This force attracts nodes to the center of the svg area
.on("end", ticked);
//.on("tick", () => this.tick());
function ticked() {
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
nodo
.attr("cx", function (d) { return d.x+6; })
.attr("cy", function(d) { return d.y-6; });
}
svg.selectAll("*").exit();
}, [props.data]);
return <svg ref={areaChart}> </svg>;
};
export default NetworkGraph;
I tried to use force, but i think i dont have to use it because i have to generate the new incoming graph every 1 second. Here add a image that i want to generate.

How to remove the previous instance from ReactJS through D3?

I would like to draw new treemap every time the data (data is generated based on the user interaction such as button clicks) is changed. At the moment every time the data is changed a new treemap is created but it is drawn on top of the previous treemap - meaning I can see both treemaps on the screen. Somehow the previous instance is not removed.
I have looked at this and this, and applied remove() function to remove the previous instance via d3. However, it does not work. I may be incorrectly used the remove function in the life cycle.
d3.select("treemap").remove(); is used in the second useEffect method.
export function Treemap({ width, height, data }) {
const ref = useRef();
useEffect(() => {
const svg = d3
.select(ref.current)
.attr("id", "treemap")
.attr("width", width)
.attr("height", height);
}, []);
useEffect(() => {
//THIS IS WHERE I USE REMOVE FUNCTION;
d3.select("treemap").remove();
draw();
}, [data]);
const draw = () => {
const svg = d3.select(ref.current);
// Give the data to this cluster layout:
var root = d3.hierarchy(data).sum(function (d) {
return d.value;
});
// initialize treemap
d3
.treemap()
.size([width, height])
.paddingTop(28)
.paddingLeft(0)
.paddingRight(0)
.paddingBottom(7)
.paddingInner(3)(root);
const color = d3
.scaleOrdinal()
.domain(["Diary", "Sweetner", "Fruit"])
.range(["#8FD175", "#402D54", "#E67E22"]);
const opacity = d3.scaleLinear().domain([10, 30]).range([0.5, 1]);
// Select the nodes
var nodes = svg.selectAll("rect").data(root.leaves());
// draw rectangles
nodes
.enter()
.append("rect")
.attr("x", function (d) {
return d.x0;
})
.attr("y", function (d) {
return d.y0;
})
.attr("width", function (d) {
return d.x1 - d.x0;
})
.attr("height", function (d) {
return d.y1 - d.y0;
})
.style("stroke", "black")
.style("fill", function (d) {
return color(d.parent.data.name);
})
.style("opacity", function (d) {
return opacity(d.data.value);
});
nodes.exit().remove();
// select node titles
var nodeText = svg.selectAll("text").data(root.leaves());
// add the text
nodeText
.enter()
.append("text")
.attr("x", function (d) {
return d.x0 + 5;
}) // +10 to adjust position (more right)
.attr("y", function (d) {
return d.y0 + 20;
}) // +20 to adjust position (lower)
.text(function (d) {
return d.data.name;
})
.attr("font-size", "19px")
.attr("fill", "white");
// select node titles
var nodeVals = svg.selectAll("vals").data(root.leaves());
// add the values
nodeVals
.enter()
.append("text")
.attr("x", function (d) {
return d.x0 + 5;
}) // +10 to adjust position (more right)
.attr("y", function (d) {
return d.y0 + 35;
}) // +20 to adjust position (lower)
.text(function (d) {
return d.data.value;
})
.attr("font-size", "11px")
.attr("fill", "white");
// add the parent node titles
svg
.selectAll("titles")
.data(
root.descendants().filter(function (d) {
return d.depth == 1;
})
)
.enter()
.append("text")
.attr("x", function (d) {
return d.x0;
})
.attr("y", function (d) {
return d.y0 + 21;
})
.text(function (d) {
return d.data.name;
})
.attr("font-size", "19px")
.attr("fill", function (d) {
return color(d.data.name);
});
};
return (
<div className="chart">
<svg ref={ref}></svg>
</div>
);
}
Normally, with d3, you never remove the already drawn nodes. It's much cheaper (computationally) and easier to just repurpose them!
If you really want to remove all nodes, d3.select("treemap") doesn't do anything, because "treemap" is not a valid selector. Try #treemap instead.
Or, if you want to repurpose the already drawn bits, consider the following:
function Treemap({
width,
height
}) {
const ref = React.useRef();
const [data, setData] = React.useState(`
{
"name": "Fruit",
"children": [
{ "name": "Apples", "value": 1 },
{ "name": "Oranges", "value": 1 },
{ "name": "Bananas", "value": 1 }
]
}
`);
React.useEffect(() => {
const svg = d3
.select(ref.current)
.attr("id", "treemap")
.attr("width", width)
.attr("height", height);
}, []);
React.useEffect(() => {
draw();
}, [data]);
const draw = () => {
const svg = d3.select(ref.current);
let parsedData
try {
parsedData = JSON.parse(data);
} catch (e) {
console.log(e);
return;
}
// Give the data to this cluster layout:
var root = d3.hierarchy(parsedData).sum(function(d) {
return d.value;
});
// initialize treemap
d3
.treemap()
.size([width, height])
.paddingTop(28)
.paddingLeft(0)
.paddingRight(0)
.paddingBottom(7)
.paddingInner(3)(root);
const color = d3
.scaleOrdinal()
.domain(["Diary", "Sweetner", "Fruit"])
.range(["#8FD175", "#402D54", "#E67E22"]);
const opacity = d3.scaleLinear().domain([10, 30]).range([0.5, 1]);
// Select the nodes
var nodes = svg.selectAll("rect").data(root.leaves());
// draw rectangles
var newNodes = nodes
.enter()
.append("rect")
.style("stroke", "black");
nodes.merge(newNodes)
.attr("x", function(d) {
return d.x0;
})
.attr("y", function(d) {
return d.y0;
})
.attr("width", function(d) {
return d.x1 - d.x0;
})
.attr("height", function(d) {
return d.y1 - d.y0;
})
.style("fill", function(d) {
return color(d.parent.data.name);
})
.style("opacity", function(d) {
return opacity(d.data.value);
});
nodes.exit().remove();
// select node titles
var nodeVals = svg.selectAll(".val").data(root.leaves());
nodeVals.exit().remove();
// add the values
var newNodeVals = nodeVals
.enter()
.append("text")
.classed("val", true)
.attr("font-size", "11px")
.attr("fill", "white");
nodeVals.merge(newNodeVals)
.attr("x", function(d) {
return d.x0 + 5;
}) // +10 to adjust position (more right)
.attr("y", function(d) {
return d.y0 + 35;
}) // +20 to adjust position (lower)
.text(function(d) {
return d.data.value;
});
// add the parent node titles
var titles = svg
.selectAll(".title")
.data(
root.descendants().filter(function(d) {
return d.depth == 1;
})
);
titles.exit().remove();
var newTitles = titles
.enter()
.append("text")
.classed("title", true)
.attr("font-size", "19px");
titles.merge(newTitles)
.attr("x", function(d) {
return d.x0 + 5;
})
.attr("y", function(d) {
return d.y0 + 21;
})
.text(function(d) {
return d.data.name;
})
.attr("fill", function(d) {
return color(d.data.name);
});
};
return ( <
div className = "chart" >
<
textarea onChange = {
(el) => setData(el.target.value)
}
value = {
data
}
rows = "20"
cols = "50" / >
<
svg ref = {
ref
} > < /svg> <
/div>
);
}
ReactDOM.render( <
Treemap width = "600"
height = "300" / > ,
document.getElementById('root')
)
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.js"></script>
<div id="root"></div>
In any case, all your selectors were missing the .-class prefix. I'd recommend to read up on selectors, and on the enter(), exit(), merge() lifecycle.

React + D3 + Force-Directed Tree + Adjustable Link Strength

I'm trying to make Force-Directed Tree with React and it works. But I cannot modify "link strength", if I pass it outside component through the props.
Honestly, I can change "strength", but I need to append d3 svg to my react ref div after that to see the changes. And whole graph will be redrawn.
I find example by Mike Bostock. He advice to modify the parameters of a force-directed graph with reheat the simulation using simulation.alpha and simulation.restart. But I cannot make it works with react. Nothing happens.
Here is my code:
export default function Hierarchy(props) {
const {
strength,
lineColor,
lineStroke,
width,
height,
nodeSize,
nodeColor,
} = props;
const root = d3.hierarchy(data);
const links = root.links();
const nodes = root.descendants();
const svg = d3.create("svg");
const link = svg
.append("g")
.selectAll("line")
.data(links)
.join("line");
const node = svg
.append("g")
.selectAll("circle")
.data(nodes)
.join("circle");
function applyStyle(selectionSVG) {
selectionSVG
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-width / 2, -height / 2, width, height]);
selectionSVG
.selectAll("circle")
.attr("r", nodeSize)
.attr("fill", nodeColor)
selectionSVG
.selectAll("line")
.attr("stroke", lineColor)
.attr("stroke-width", lineStroke);
}
applyStyle(svg);
const divRef = React.useRef(null);
const linkForce = d3
.forceLink(links)
.id(d => d.id)
.distance(0)
.strength(strength);
const simulation = d3
.forceSimulation(nodes)
.force("link", linkForce)
.force("charge", d3.forceManyBody().strength(-500))
.force("x", d3.forceX())
.force("y", d3.forceY());
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node.attr("cx", d => d.x).attr("cy", d => d.y);
});
//ComponentDidMount
useEffect(() => {
//Append d3 svg to ref div
var div = d3.select(divRef.current);
if (div.node().firstChild) {
div.node().removeChild(div.node().firstChild);
}
div.node().appendChild(svg.node());
}, []);
//ComponentDidUpdate
useEffect(() => {
simulation.force("link").strength(strength);
simulation.alpha(1).restart();
}, [strength]);
//ComponentDidUpdate
useEffect(() => {
var div = d3.select(divRef.current);
applyStyle(div.select("svg"));
});
//Render
return <div id="hierarchyTree" ref={divRef} />;
}
Here is Sandbox.
I find solution, if anybody interesting.
The fact is simulation was not saved when component was updated. So I create ref for it.
const simulationRef = React.useRef(simulation)
and replace it in useEffect section
//ComponentDidUpdate
useEffect(() => {
simulationRef.current.force("link").strength(strength)
simulationRef.current.alpha(1).restart()
console.log(simulationRef.current)
}, [strength])
After that everything works fine.

passing data from a react based component to vanilla js class

I am trying to pass data from react class base component to a vanillajs class so this class is able to render D3 bar chart ,
I've tried passing the data from the react component through the contractor of the vanilla class , i have the data available in the vanilla class when i try to consol log it , but when i want to call the data variable in the method call d3.data() it is empty , here is the code
React class
//imports..
const _data = []
const firebaseConfig = {
//configuration ..
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore()
class TableOfD3 extends Component {
constructor(){
super()
this.svgId = `SVG_${uuid()}`
}
getData(){
db.collection('db').get().then( res=>{
res.docs.forEach(doc => {
_data.push(doc.data())
})
}
componentDidMount(){
this.start()
}
componentDidUpdate(){
this.start()
}
start(){
this._graph = new D3TableEngine('#' + this.svgId,_data)
this._graph.start()
}
render() {
return (
<div>
<svg id={this.svgId}></svg>
</div>
);
}
}
export default TableOfD3;
// vanillajs class
export default class D3TableEngine {
constructor(svgId, passedData) {
this._svg = d3.select(`${svgId}`);
this._svg.attr('width', _WIDTH)
this._svg.attr('height', _HEIGHT)
this._passedData = passedData
}
start() {
const self = this;
var _g = self._svg;
const graphWidth = _WIDTH - _MARGIN.left - _MARGIN.right
const graphHeight = _HEIGHT - _MARGIN.top - _MARGIN.bottom
const graph = _g.append('g')
.attr('width', graphWidth)
.attr('height', graphHeight)
.attr('transform', `translate(${_MARGIN.left + 20}, ${_MARGIN.top})`)
const xAxisGroup = graph.append('g')
.attr('transform', `translate(0,${graphHeight })`)
const yAxisGroup = graph.append('g')
const yScale = d3.scaleLinear()
.domain([0,d3.max(self._passedData, (d) => d.orders)])
.range([graphHeight,0])
const xScale = d3.scaleBand()
.domain(self._passedData.map((el) => el.name))
.range([0,500])
.paddingInner(0.2)
.paddingOuter(0.2)
const rects = graph.selectAll("rect").data(self._passedData);
rects
.attr("x", (d)=> xScale(d.name))
.attr("y", (d) => yScale( d.orders))
.attr("height", (d)=> graphHeight - yScale( d.orders))
.attr("width", xScale.bandwidth)
.attr('fill', 'blue')
rects
.enter()
.append("rect")
.attr("x", (d)=> xScale(d.name))
.attr("y", (d) => yScale( d.orders))
.attr("height", (d)=> graphHeight - yScale( d.orders ))
.attr("width", xScale.bandwidth)
.attr('fill', 'blue')
const xAxis = d3.axisBottom(xScale)
xAxisGroup.call(xAxis)
const yAxis = d3.axisLeft(yScale)
.ticks(5)
.tickFormat((d) => 'Orders ' +d )
yAxisGroup.call(yAxis)
xAxisGroup.selectAll('text')
.attr('transform', 'rotate(-40)' )
.attr('text-anchor', 'end')
} )
}
refresh() {}
}
I re-wrote your React class because you were doing many things that would be considered anti-pattern. In general, you want to shove as much as you can in this.state. Otherwise, you miss out on the main advantage of React - and that is optimally re-rendering the DOM when variables change. I think the main issue you're likely having is that you're updating the DOM from componentDidUpdate(), which will fire another update. It'll continue infinitely and crash. I would strongly recommend refactoring D3TableEngine into a React Component instead of a plain JS class. The challenge is that the way you have written the d3 component, it has to be destroyed and re-created for each render, which is a problem because React doesn't know what to do other than re-create it.
import React, { Component } from 'react';
class TableOfD3 extends Component {
constructor() {
super();
const firebaseConfig = {
//configuration ..
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
this.state = {
svgId: `SVG_${uuid()}`,
data: [],
db: db
};
}
componentDidMount() {
const response = await this.state.db.collection('db').get();
const data = response.docs.map(doc => doc.data());
this.setState({
data
});
}
componentDidUpdate() {
}
render() {
return (
<div>
<D3TableEngine
id={this.state.svgId}
data={this.state.data}
/>
</div>
);
}
}
UPDATE: I gave a shot at refactoring your d3 class into a React Component. The important pieces here are the ref, which let's you get a reference to the element so redraw can execute all the d3 code on the right svg element. Then, inside componentDidMount and componentDidUpdate, you must call redraw. However, I would refactor the redraw method to break out the parts that will change from the parts that will not change (eg: move the graph pieces into a different function and call that in componentDidUpdate). We do this so that React is performing as expected and only updating the elements in the DOM that have changed. If you need additional help, you may take a look at this jsfiddle example/medium article.
const MARGIN = 0;
const WIDTH = 0;
const HEIGHT = 0;
class D3TableEngine extends Component {
componentDidMount() {
redraw();
}
componentDidUpdate() {
redraw();
}
redraw = () => {
this.svg = d3.select(this.svg);
const graphWidth = WIDTH - MARGIN.left - MARGIN.right
const graphHeight = HEIGHT - MARGIN.top - MARGIN.bottom
const graph = this.svg.append('g')
.attr('width', graphWidth)
.attr('height', graphHeight)
.attr('transform', `translate(${_MARGIN.left + 20}, ${_MARGIN.top})`)
const xAxisGroup = graph.append('g')
.attr('transform', `translate(0,${graphHeight})`)
const yAxisGroup = graph.append('g')
const yScale = d3.scaleLinear()
.domain([0, d3.max(props.data, (d) => d.orders)])
.range([graphHeight, 0])
const xScale = d3.scaleBand()
.domain(props.data.map((el) => el.name))
.range([0, 500])
.paddingInner(0.2)
.paddingOuter(0.2)
const rects = graph.selectAll("rect").data(props.data);
rects
.attr("x", (d) => xScale(d.name))
.attr("y", (d) => yScale(d.orders))
.attr("height", (d) => graphHeight - yScale(d.orders))
.attr("width", xScale.bandwidth)
.attr('fill', 'blue')
rects
.enter()
.append("rect")
.attr("x", (d) => xScale(d.name))
.attr("y", (d) => yScale(d.orders))
.attr("height", (d) => graphHeight - yScale(d.orders))
.attr("width", xScale.bandwidth)
.attr('fill', 'blue')
const xAxis = d3.axisBottom(xScale)
xAxisGroup.call(xAxis)
const yAxis = d3.axisLeft(yScale)
.ticks(5)
.tickFormat((d) => 'Orders ' + d)
yAxisGroup.call(yAxis)
xAxisGroup.selectAll('text')
.attr('transform', 'rotate(-40)')
.attr('text-anchor', 'end')
}
render() {
return (
<svg
id={this.props.svgId}
width={WIDTH}
height={HEIGHT}
ref={el => (this.svg = d3.select(el))}
>
</svg>
);
}
}

Missing rects in bar chart

I'm new to react and d3. I'm trying our barChart but only see one overlapped rect. Examining each rect element, I see that x, y, height and width are expected. But I don't understand why the other 3 rect are not shown.
BarChart.js
import React, { Component } from 'react'
import { scaleLinear } from 'd3-scale';
import { max } from 'd3-array';
import { select } from 'd3-selection';
export default class BarChart extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.createBarChart()
}
componentDidUpdate() {
this.createBarChart()
}
createBarChart = () => {
const node = this.node
const dataMax = max(this.props.data)
const yScale = scaleLinear()
.domain([0, dataMax])
.range([0, this.props.size[1]])
select(node)
.selectAll('rect')
.data(this.props.data)
.enter() // placeholder selection
.append('rect') // return a selection of appended rects
select(node)
.selectAll('rect') // rect selection
.data(this.props.data) // update data in rect selection
.exit()
.remove() // exit and remove rects
select(node)
.selectAll('rect') // rect selection
.data(this.props.data) // join data with rect selection
.style('fill', '#fe9922')
.attr('x', (d, i) => i * 25)
.attr('y', d => this.props.size[1] - yScale(d))
.attr('height', d => yScale(d))
.attr('width', 25)
}
render() {
return (
// Pass a reference to the node for D3 to use
<svg ref={node => this.node = node}
width={this.props.width} height={this.props.height}
>
</svg>
)
}
}
With this answer, I've updated createBarChart() but still seeing the same odd rendering.
createBarChart = () => {
const node = this.node
const dataMax = max(this.props.data)
const yScale = scaleLinear()
.domain([0, dataMax])
.range([0, this.props.size[1]])
this.rects = select(node)
.selectAll('rect')
.data(this.props.data)
this.rects
.exit()
.remove()
this.rects = this.rects.enter()
.append('rect')
.merge(this.rects)
.style('fill', '#fe9922')
.attr('x', (d, i) => i * 25)
.attr('y', d => this.props.size[1] - yScale(d))
.attr('height', d => yScale(d))
.attr('width', 25)
}
App.js
<div>
<BarChart data={[50,10,11,13]} size={[500,500]}/>
</div>
Found the bug, I passed in wrong props, this.props.width and this.props.height doesn't exist in this case. As height of my rect overflows the svg box, I can only see one longest bar, but not the other shorter ones.
<svg ref={node => this.node = node}
width={this.props.size[0]} height={this.props.size[1]}
>
</svg>

Resources