d3 v4 getting data for bar graph tooltip - javascript

I am able to get a tooltip to work by defining the text but for the life of me I cannot get the tooltip to print text from a data file. I feel like I am messing up defining d.value even though it is being graphed just fine but I also wonder if there is something with v4 that I don't know about. I've tried moving the var statement all over the place but nothing seems to help. It usually ends up being a "Cannot read property of undefined" error. Any thoughts on what I'm doing wrong? Thanks.
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("This works just fine");
/* .text(function(d) { return d.value; }); */
d3.tsv("15.tsv", type, function(error, data) {
if (error) throw error;
x.domain([0, d3.max(data, function(d) { return d.value; })]);
y.domain(data.map(function(d) { return (d.gamedate); }))
.paddingInner(0.1)
.paddingOuter(0.5);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("transform", "translate(" + width + ",0)")
.attr("y", 15)
.style("text-anchor", "end")
.text("Game Score");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("height", y.bandwidth())
.attr("y", function(d) { return y(d.gamedate); })
.attr("width", function(d) { return x(d.value); })
.on("mouseover", function(d){
return tooltip.style("visibility", "visible");})
.on("mousemove", function(d){return tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+400)+"px");})
.on("mouseout", function(d){return tooltip.style("visibility", "hidden");})

I think the main issue is that event variable is not defined in the scope of the mousemove function. You can get the mouse values by doing the following:
.on("mousemove", function(d) {
const [xMouse, yMouse] = d3.mouse(this);
tooltip.style("top", (yMouse) + "px")
.style("left", (xMouse) + "px")
.text(`Gamedate ${d.gamedate} with value ${d.value}`)
})
I made a JSbin in order to show how I got it to work, the data is mocked.

Related

D3: Why tooltip near cursor never shows?

I'm trying to make a d3 tooltip that can show near my cursor when I hover over a dot. I tried lots of methods available online, but none of them works. The tooltip doesn't show, and there is no error messages in console. Could anyone help me with this? My code is as follows:
I suspect there might be some issue with svg, but not sure how to solve it.
var svg = d3.select("#linechart").append("svg").attr('id','cases')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xScale = d3.scaleTime()
.domain(d3.extent(getCovidDate(data,state), function(d){return new Date(d)}))
.range([0, width]);
var yScale = d3.scaleLinear()
.domain(d3.extent(getCases(data,state), function(d){return d}))
.range([height, 0]);
var line = d3.line()
.x(function(d) { return xScale(new Date(d[0])); }) // set the x values for the line generator
.y(function(d) { return yScale(d[1]); }) // set the y values for the line generator
.curve(d3.curveMonotoneX) // apply smoothing to the line
var dataset = d3.zip(getCovidDate(data,state),getCases(data,state))
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale)); // Create an axis component with d3.axisBottom
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale)); // Create an axis component with d3.axisLeft
var div = d3.select("#cases").append("div")
.attr("class", "tooltip")
.style("display", "none");
svg.append("path")
.datum(dataset) // Binds data to the line
.attr("class", "line") // Assign a class for styling
.attr("d", line) // Calls the line generator
.style('fill-opacity', 0)
.style('stroke','cadetblue')
.on('mouseover', function (d, i) {
d3.select(this).transition()
.duration('50')
.attr('opacity', '.55')})
.on('mouseout', function (d, i) {
d3.select(this).transition()
.duration('50')
.attr('opacity', '1')});
svg.selectAll(".dot")
.data(dataset)
.enter().append("circle")
.attr("class", "dot") // Assign a class for styling
.attr("cx", function(d) { return xScale(new Date(d[0])) })
.attr("cy", function(d) { return yScale(d[1]) })
.attr("r", 5)
.style("fill",'cadetblue')
.on('mouseover', function (d, i) {
d3.select(this).transition()
.duration('50')
.attr('opacity', '.55')
div.style("display", "inline");
})
.on('mousemove',function(d){
div.text(d[1])
.style("left", (d3.event.pageX + 10) + "px")
.style("top", (d3.event.pageY - 15) + "px")
})
.on('mouseout', function (d, i) {
d3.select(this).transition()
.duration('50')
.attr('opacity', '1')
div.style("display", "none");
});
svg.append("line")
.attr("x1", xScale(new Date(inputValue)))
.attr("y1", 0)
.attr("x2", xScale(new Date(inputValue)))
.attr("y2", height)
.style("stroke-width", 2)
.style("stroke", "red")
.style("fill", "none");
d3.select('#cases').remove()

D3JS refreshing graph for new Data

I'm trying to update the graph with a new csv file (data2.csv) by calling update but the graph isnt changing. The code as below is the function that would be called when I click a button.
Plnkr is the sample code..
Do advice!
http://plnkr.co/edit/pOYqmaOxy1lmY82jlhfA
<script>
function update(){
d3.csv("data2.csv", function(error, data) {
if (error) throw error;
var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
data.forEach(function(d) {
d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
});
x0.domain(data.map(function(d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.ages, function(d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
}
</script>
You say you want to update an existing graph with your update function and new data coming from an csv after some event occurs, correct?
D3 stands for Data Driven Documents, so your data is very important when drawing graphs. D3 works with selections (or collections if that works better for you) based on the data you want to display.
Say you want a barchart displaying the following array: [10,20,30]. The height of the bars is in function with the data in the array.
creating new elements
If you dont have bar elements on the page already, that means you will need to 'append' them to the graph. This is usually done with a code pattern resembling like:
svg.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
With this code, you take the svg variable (which is basically a d3 selection containing one element, the svg) and you select all "rect" elements on the page but inside the svg element. There are none at this very moment, remember, you are going to create them. After the selectAll, you see the data function which specifies the data that will be bound to the elements. Your array contains 3 pieces of data, that means that you expect ot see 3 bars. How will D3 know? It will because of the .enter() (meaning: which elements are not on the graph yet?) and the .append(element) functions. The enter function basically means: In my current d3 selection (being selecAll('rect') ), how many of the specified elements do i need to append? Since you current selection is empty (you dont have 'rect' elements yet), and d3 spots 3 pieces of data in your data function, using .append() it will create and append 3 elements for you. With the attr fuctions you can specify how the elements will look like.
updating elements
Suppose my array of [10,20,30] suddenly changes to [40,50,60]. notice something very important here, my array still contains 3 pieces of data! It is just their value that changed!
I would really want to see my bars reflecting this update! (and i think your case matches this one).
But if I use this pattern again, what will happen?
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
...
The state.selectAll("rect") selection contains 3 elements, d3 checks how many pieces of data you have (still 3) and it sees that it doesnt need to append anything!
Does that mean you cannot update with D3? Absolutely not! It is just much simpler then you would think :-).
If i would want to update my bars so that their height reflects the new values of my data, I should do it like this:
state.selectAll("rect")
.data(function(d) { return d.ages; })
.attr("height", function(d) { return height - y(d.value); });
Basically, I select all my rects, I tell d3 what data i am working on and then I simply tell d3 to alter the height of of my rect. You can even do it with a transition! (more info on transitions here ). I think this is what you need to do, instead of appending the "rect" elements again.
Updating elements, part 2
continuing with my example, what do to if my array all of a sudden wouuld be like this: [100,200,300, 400]? Note that my values changed again BUT there is an extra element there!!
Well, when handling the event (for example a click on a button, or a submit of data) that changes the data, you need to tell D3 that it will need to append something and update the existing bars. This can simply be done by doing coding both patterns:
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.attr("height", function(d) { return height - y(d.value); });
Removing elements
What if my data array would suddenly only consist of only 2 pieces of data: [10,20] ?
Just like there is a function for telling d3 that it needs to append something, you can tell it that it what to do with elements that dont seem to have data to be bound on anymore:
svg.selectAll("rect")
.data(function(d) { return d.ages; })
.exit().remove();
The exit function matches the amount of pieces of data you have vs the amount of selected elements. The exit function then tells d3 to drop those elements.
I hope this was helpfull. It is a bit of a basic explanation (its a little more complicated then that) but I had to hurry, so if there should be questions or errors, please tell me.
d3.csv("data2.csv", function(error, data) {
if your server is caching this reference - try a Math.random() :D
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
This will force(ish) a refresh of data - could be costly so triage according to your needs via a serverside process
edit:
d3.csv("data2.csv?=" + (Math.random() * (100 - 1) + 1), function(error, data) {
would be the alteration. Its sloppy but illustrates how to suggestively force a cache refresh
You can do it like this:
Make a buildMe() function which makes the graph.
function buildMe(file) {//the file name to display
d3.csv(file, function(error, data) {
if (error) throw error;
var ageNames = d3.keys(data[0]).filter(function(key) {
return key !== "State";
});
data.forEach(function(d) {
d.ages = ageNames.map(function(name) {
return {
name: name,
value: +d[name]
};
});
});
x0.domain(data.map(function(d) {
return d.State;
}));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) {
return d3.max(d.ages, function(d) {
return d.value;
});
})]);
svg.selectAll("g").remove();//remove all the gs within svg
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) {
return "translate(" + x0(d.State) + ",0)";
});
state.selectAll("rect")
.data(function(d) {
return d.ages;
})
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) {
return x1(d.name);
})
.attr("y", function(d) {
return y(d.value);
})
.attr("height", function(d) {
return height - y(d.value);
})
.style("fill", function(d) {
return color(d.name);
});
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 20 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) {
return d;
});
});
}
Then on Load do this buildMe("data.csv");
On button click do this
function updateMe() {
console.log("Hi");
buildMe("data2.csv");//load second set of data
}
Working code here
Hope this helps!

D3: refactoring data source from .tsv to locally stored array [duplicate]

This question already has answers here:
D3js take data from an array instead of a file
(2 answers)
Closed 7 years ago.
I have the following D3 configuration, which reads-in data from an external .tsv file:
d3.tsv("path/data.tsv", type, function(error, data) {
if (error) throw error;
x.domain(data.map(function(d) { return d.label; }));
y.domain([0, d3.max(data, function(d) { return d.count; })]);
svg.append("g")
.attr("class", "x axis")
.call(xAxis)
.text("x-axis label");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("y-axis label");
svg.selectAll(".bar")
.data(graphData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.label); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.count); })
.attr("height", function(d) { return height - y(d.count); });
});
I want to instead load data from a locally stored array, which takes the form
var graphData = [
{label: '0', count: 0},
{label: '0', count: 0}
];
I'm having a lot of trouble refactoring this. In particular, I don't know how to maintain everything in the d3.tsv callback. With .tsv, everything has to wait for the data to download, but I just need this stored variable to be my data now. I thought I could just do a d3.data function, but evidentally not. I also looked into using d3.json, but I need to access the data internally, not by pulling in a separate .json file.
Just drop the d3.tsv() part and use the callback code directly.
Your graphData should replace the data parameter of the callback, but the rest should work unchanged.
var graphData = [
{label: '0', count: 0},
{label: '0', count: 0}
];
x.domain(graphData.map(function(d) { return d.label; }));
y.domain([0, d3.max(graphData, function(d) { return d.count; })]);
svg.append("g")
.attr("class", "x axis")
.call(xAxis)
.text("x-axis label");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("y-axis label");
svg.selectAll(".bar")
.data(graphData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.label); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.count); })
.attr("height", function(d) { return height - y(d.count); });

Smoothen transition for order of bars in d3 chart

I am allowing users to order the data in their bar chart either chronologically or in descending order from highest to lowest based on a metric of their choosing.
The height of the bars themselves are smoothly transitioning, but when descending order is chosen, the order of the array of data changes, meaning the order of the bars need to change as well. Right now, the new data in this case just flashes its update (without any smooth animation). Where would I build in this additional transition? Or even better, how would I target this?
scope.render = function(data){
if (scope.metric !== "") {
var maximumY = d3.max(data, function(d) {
return eval('d.' + scope.metric);
});
x.domain(data.map(function(d) { return d.id; }));
y.domain([-(maximumY * .01), d3.max(data, function(d) { return eval('d.' + scope.metric); })]);
chart.select(".x.axis").remove();
chart
.append("g")
.append("line")
.attr('x1',0)
.attr('x2',width)
.attr('y1',height )
.attr('y2',height)
.attr('stroke-width','2')
.attr("class", "domain");
chart.select(".y.axis").remove();
chart.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -40)
.attr('class','label')
.attr("x", -height)
.attr("dy", ".71em")
.style("text-anchor", "begin")
.text(scope.label);
var bar = chart.selectAll(".bar")
.data(data, function(d) { return d.id; });
// new data:
bar.enter()
.append("g")
.attr("class", "bar-container")
.append("rect")
.attr("class", "bar")
.attr('fill','#4EC7BD')
.attr("x", function(d) { return x(d.id); })
.attr("y", function(d) { return y(eval('d.'+scope.metric)); })
.attr("height", function(d) { return height - y(eval('d.'+scope.metric)); })
.attr("width", x.rangeBand())
.on('click', function(d){
scope.showDetails(d, eval('d.'+scope.metric))
})
// removed data:
bar.exit().remove();
// updated data:
bar
.transition()
.duration(750)
.attr("y", function(d) { return y(eval('d.'+scope.metric)); })
.attr("height", function(d) { return height - y(eval('d.'+scope.metric)); });
}
};
Let me know if there is anything additional I can provide.

Struggling to get a chart with modified JSON format

I'm very new to d3js. I did a bar chart using one json file. It works very fine. But now I changed the JSON file format due to some unavoidable reasons.My previous json was:
[
{"name":"bike","value":98},
{"name":"car","value":52},
{"name":"bus","value":20},
{"name":"van","value":65}
]
Code is :
d3.json("sample.json", function(error, data) {
x.domain(data.map(function(d) { return d.name; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);
var chart = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = chart.selectAll(".bar")
.data(data)
.enter().append("g");
bar.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("width", x.rangeBand())
.attr("height", function(d) { return height - y(d.value); });
});
This is my new json file:
[
{"category":"bike","bike":38,"car":0,"bus":0,"van":0},
{"category":"car","bike":0,"car": 50,"bus":0,"van":0,},
{"category":"bus","bike":0,"car": 0,"bus":14,"van":0},
{"category":"van","bike":0,"car": 0,"bus":0,"van":43}
]
I want to get a chart like same as previous one. Data with "0" (zero) shouldn't appear in chart.
Pls help me. Thanks in advance :)
You don't provide an explanation of your new format, and I'm not sure how your previous format was working (given the x attribute setting) but adjusting to the new format should be as simple as
.attr("x", function(d) { return x(d.category); })
.attr("y", function(d) { return y(d[d.category]); })
And similar changes elsewhere. (e.g. for the height)
Or maybe I'm missing something?

Categories