I spent hours trying to figure out why my code was not working. I then arbitrarily moved my button code from after the D3 code (at the end between </script> and </body>) to the top (between <script type="text/javascript"> and <body>). It works now, but I don't know why. I don't want to make this mistake again or confuse myself in the future.
<body>
<button>Update</button>
<script type="text/javascript">
var w = 500;
var h = 500;
var barPadding = 1;
var dataset = [ ];
for (var i = 0; i < 14; i++) {var newNumber = Math.round(Math.random() * 70);
dataset.push(newNumber);}
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create Scales for Data conversion
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d,i) {return d;})]) //input
.range([0,w]); // output
var yScale = d3.scale.ordinal()
.domain(d3.range(dataset.length))
.rangeRoundBands([0, h], 0.05); //Vertical separation + barpadding
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", 3)
.attr("y", function (d,i) {return yScale(i);})
.attr("width", function(d,i) {return xScale(d);})
.attr("height", yScale.rangeBand())
.attr("fill", function(d) {return "rgb(" + (d * 10) + ", 0,0 )";});
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {return d;})
.attr("x", function(d) {return xScale(d) -15;})
.attr("y", function(d, i) {return yScale(i) +5 +yScale.rangeBand() / 2;})
.attr("fill", "white")
.attr("font-family", "sans-serif")
.attr("text-anchor", "middle");
//Create Data Update and transition
d3.select("button")
.on("click", function() {
//New values for dataset
dataset = [ ];
for (var i = 0; i < 14; i++) {var newNumber = Math.round(Math.random() * 70);
dataset.push(newNumber);}
//Update all rects, and color gradient
svg.selectAll("rect")
.data(dataset)
.transition()
.attr("x", 3)
.attr("width", function(d,i) {return xScale(d);})
.attr("fill", function(d) {return "rgb(" + (d * 10) + ", 0,0 )";});
//Update text label and position
svg.selectAll("text")
.data(dataset)
.text(function(d) {return d;})
.attr("x", function(d) {return xScale(d) -15;})
.attr("y", function(d, i) {return yScale(i) +5 + yScale.rangeBand() / 2;});
});
</script>
</body>
If you're saying that the code as shown in your question works, with the <button> element before the <script> element, it's because <script> elements are executed as the browser encounters them, top-to-bottom while parsing the page. Which means that any JavaScript that you use is only able to reference elements that are higher in the page source because the browser doesn't know about the later elements yet.
Unless you have code within functions that don't get called until after the DOM is complete, for example if you assign a DOM ready or onload event handler, or a delegated click handler or something.
Related
I have a D3 visualization with a map and a bar chart. I am trying to get the bar chart to change depending on which circle on the map is clicked. Not sure how to do this. I have a function in my bar_chart.js file named update(newData) and a few extra arrays for the different circles on the map. Here is the link to the bl.ocks for the map and bar char.
js code for map
var myData = [21, 3, 5, 21, 15];
//Width and height
var w = 200;
var h = 125;
var yScale = null;
function draw(initialData) {
var xScale = d3.scale.ordinal()
.domain(d3.range(initialData.length))
.rangeRoundBands([0, w], 0.05);
yScale = d3.scale.linear()
.domain([0, d3.max(initialData)])
.range([0, h]);
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(initialData)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", "steelblue");
svg.selectAll("text")
.data(initialData)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
}
draw(myData);
//update function
function update(newData) {
yScale.domain([0, d3.max(newData)]);
var rects = d3.select("#chart svg")
.selectAll("rect")
.data(newData);
// enter selection
rects
.enter().append("rect");
// update selection
rects
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
// exit selection
rects
.exit().remove();
var texts = d3.select("#chart svg")
.selectAll("text")
.data(newData);
// enter selection
texts
.enter().append("rect");
// update selection
texts
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.text(function(d) {
return d;
})
// exit selection
texts
.exit().remove();
}
var mk = [10,17,20,14,8];
var cn = [18,4,9,20,15];
var nd = [5,12,7,15,21];
d3.select("#update").on("click", function() { update(newData); });
You have to incorporate the barchart data in your cities.csv file.
In the on-click handler of cities.csv where you show the tooltip you have to transform the data from the CSV into an array and call the bar chart update() method with this array.
One way of doing is to replace the , from the bar chart data with another char and split the string and convert the parts to numbers.
var cityData = d.barchart.split('#').map(Number);
update(cityData);
You also have to set the attributes of the new rects and texts of the bar chart. And the x-position will change if the number of bars change.
I am trying to plot a moving average on top of a candlestick chart but the "path" is not appearing completely on the svg canvas that I created.
I have tried looking at several post on how to put a line on top of a bar graph (because I figured it would be similar) but it has not worked.
A couple of the examples and post I have looked at are below:
https://bl.ocks.org/nanu146/f48ffc5ec10270f55c9e1fb3da8b38f0
d3.js How to add lines to a bar chart
D3.js combining bar and line chart
I have all the data in a array.
I am using the same x "scale" for both the candle stick graph and the moving average (line). I have tried using the same y "scale" for both the line and the candlestick but it did not work. Therefore i tried creating 2 scales for y, one for the moving average and one for the candlestick chart. That is what Im doing in my code below.
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript">
var twoHundredDayCandleStickChart = [];
//pulling from 2 properties so must do this way
#for (int i = 0; i != 100; ++i)
{
#:twoHundredDayCandleStickChart.push({date: '#Model.DailyTimeSeriesData.Data.ElementAt(i).Key', high: '#Model.DailyTimeSeriesData.Data.ElementAt(i).Value.high', low: '#Model.DailyTimeSeriesData.Data.ElementAt(i).Value.low', open: '#Model.DailyTimeSeriesData.Data.ElementAt(i).Value.open', close: '#Model.DailyTimeSeriesData.Data.ElementAt(i).Value.close', sma: '#Model.TwoHundredDaySma.Data.ElementAt(i).Value.Sma'})
}
console.log(twoHundredDayCandleStickChart);
var width = 900;
var height = 500;
var margin = 50;
function min(a, b) { return a < b ? a : b; }
function max(a, b) { return a > b ? a : b; }
//y for the candlestick
var y = d3.scaleLinear().range([height - margin, margin]);
var x = d3.scaleTime().range([margin, width - margin]);
//y for the line
var y1 = d3.scaleLinear().range([height - margin, margin]);
//line for the sma
var line1 = d3.line()
.x(function (d) { return x(d["date"]); })
.y(function (d) { return y(d["sma"]); });
function buildChart(data) {
data.forEach(function (d) {
d.date = new Date(d.date);
d.high = +d.high;
d.low = +d.low;
d.open = +d.open;
d.close = +d.close;
d.sma = +d.sma;
});
var chart = d3.select("#twoHundredDaySmaWithCandleStickChart")
.append("svg")
.attr("class", "chart")
.attr("width", width)
.attr("height", height);
//map is going to create an array with all the lows and then d3.min will take the min out of all of them
y.domain([d3.min(data.map(function (x) { return x["low"]; })), d3.max(data.map(function (x) { return x["high"]; }))])
x.domain(d3.extent(data, function (d) { return d["date"]; }))
y1.domain(d3.extent(68, d3.max(data, function (d) { return d["sma"]; })))
//grid for the chart; x and y axis
chart.selectAll("line.x")
.data(x.ticks(10))
.enter().append("line")
.attr("class", "x")
//.text(String)
.attr("x1", x)
.attr("x2", x)
.attr("y1", margin)
.attr("y2", height - margin)
.attr("stroke", "#ccc");
chart.selectAll("line.y")
.data(y.ticks(10))
.enter().append("line")
.attr("class", "y")
.attr("x1", margin)
.attr("x2", width - margin)
.attr("y1", y)
.attr("y2", y)
.attr("stroke", "#ccc");
//x axis
chart.append("g")
.attr("transform", "translate(0," + 450 + ")") //need to change this 450 to a variable- it is how far down the axis will go
.attr("class", "xrule") // give it a class so it can be used to select only xaxis labels or change color
//the x axis
.call(d3.axisBottom(x))
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", function (d) {
return "rotate(-65)"
});
//the y axis
chart.selectAll("text.yrule")
.data(y.ticks(10))
.enter()
.append("text")
.attr("class", "yrule")
.attr("x", 0)
.attr("y", y)
.attr("dy", 0)
.attr("dx", 20)
.attr("text-anchor", "middle")
.text(String);
//add rectangles- if open higher then close then red
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", function (d) { return x(d["date"]); })
.attr("y", function (d) { return y(max(d["open"], d["close"])); })
.attr("height", function (d) { return y(min(d["open"], d["close"])) - y(max(d["open"], d["close"])); })
.attr("width", function (d) { return 0.5 * (width - 2 * margin) / data.length; })
.attr("fill", function (d) { return d["open"] > d["close"] ? "red" : "green"; });
//add a stem to the rectangle
chart.selectAll("line.stem")
.data(data)
.enter().append("line")
.attr("class", "stem")
.attr("x1", function (d) { return x(d["date"]) + 0.25 * (width - 2 * margin) / data.length; })
.attr("x2", function (d) { return x(d["date"]) + 0.25 * (width - 2 * margin) / data.length; })
.attr("y1", function (d) { return y(d["high"]); })
.attr("y2", function (d) { return y(d["low"]); })
.attr("stroke", function (d) { return d.open > d.close ? "red" : "green"; });
chart.append("path")
.data([data])
.attr("d", line1)
.attr("class", "line")
.style("stroke", "white")
.attr("fill", "none")
.attr("stroke-width", 2);
}
buildChart(twoHundredDayCandleStickChart);
</script>
The above code is giving me the image below:
The problem in the chart above was my scales! I was taking the domain for the candle stick data but the line data was a lot lower of a min. Therefore the whole graph was not showing up on the scale because the min of the domain had to be adjusted. MANY hours wasted but hopefully this can save someone else time!
d3.select("#twoHundredDaySmaWithCandleStickChart")
Try to change the above code like below
d3.select("svg") or give the div Id
I am attempting to add a simply bar chart to my tooltip; it consists of 2 variables -- men and women. I was hoping someone might be able to help me put this inside of the tooltip instead of appending it to where it is currently being appended. I've given this a particular area to be appended just so that I know that it is, in fact, showing up(which it is), but I don't know how to get it into the tool tip. Any help is much appreciated. Oh, and this needs to be done in d3, which is partial to why I am asking this question -- I saw a similar question that wasn't implemented in pure d3, and I couldn't completely follow what was going on to emulate it in this example.
.on("mouseover", function(d)
{
tip.show(d);
var state = d.properties.name;
var men = d.properties.men;
var women = d.properties.women;
var dataset = [men, women];
var barHeight = 20;
var x = d3.scale.linear()
.domain([0, d3.max(dataset)])
.range([0, width/2]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * dataset.length);
var bar = chart.selectAll("g")
.data(dataset)
.enter().append("g")
.attr("transform", function(d, i)
{
return "translate(0," + i * barHeight + ")";
});
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d)
{
return x(d)/2+5;
})
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d)
{
return "$" + d;
});
})
Since you didn't shared the whole code to create the chart, this answer will deal with your question's title only:
How to create a chart inside a tooltip?
I'm not a d3.tip() user, since I create my own tooltips. But what you want is not complicated at all: As the tooltips are <div> elements, you can definitely add a SVG inside them.
However, you have to know where to create the SVG. So, in the following demo, I'm creating this d3.tip tooltip:
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([20, 120])
.html("<p>This is a SVG inside a tooltip:</p>
<div id='tipDiv'></div>");
//div ID here --^
The important part here is this: there is a inner <div> inside the d3.tip div, with a given ID (in that case, tipDiv). I'm gonna use that ID to create my SVG inside the tooltip:
selection.on('mouseover', function(d) {
tool_tip.show();
var tipSVG = d3.select("#tipDiv")
//select the div here--^
.append("svg")
//etc...
})
Here is the demo:
var svg = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 300);
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([20, 120])
.html("<p>This is a SVG inside a tooltip:</p><div id='tipDiv'></div>");
svg.call(tool_tip);
var data = [14, 27, 19, 6, 17];
var circles = svg.selectAll("foo")
.data(data)
.enter()
.append("circle");
circles.attr("cx", 50)
.attr("cy", function(d, i) {
return 20 + 50 * i
})
.attr("r", function(d) {
return d
})
.attr("fill", "teal")
.on('mouseover', function(d) {
tool_tip.show();
var tipSVG = d3.select("#tipDiv")
.append("svg")
.attr("width", 200)
.attr("height", 50);
tipSVG.append("rect")
.attr("fill", "steelblue")
.attr("y", 10)
.attr("width", 0)
.attr("height", 30)
.transition()
.duration(1000)
.attr("width", d * 6);
tipSVG.append("text")
.text(d)
.attr("x", 10)
.attr("y", 30)
.transition()
.duration(1000)
.attr("x", 6 + d * 6)
})
.on('mouseout', tool_tip.hide);
.d3-tip {
line-height: 1;
padding: 6px;
background: wheat;
border-radius: 4px solid black;
font-size: 12px;
}
p {
font-family: Helvetica;
}
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>
<p>Hover over the circles:</p>
I am trying to adopt bar chart example here to understand data joins in d3 v4. Enter selection works fine but I am unable to figure out how to update. Here is what I have so far: https://jsfiddle.net/hackygkL/
Can someone please help me.
var width = 420,
barheight = 30;
var svg = d3.select('#bar-chart')
.append('svg')
.attr('width', width + 50)
.attr('height', 1000);
var scale = d3.scaleLinear()
.range([0, width]);
function createBar(data) {
scale.domain([0, d3.max(data)]);
var barGroups = svg.selectAll('g')
.data(data, function(d){return d;});
barGroups.exit().remove();
var enterGroup = barGroups.enter() //ENTER
.append('g')
.merge(barGroups) //UPDATE
.attr("transform", function(d, i){
return "translate(0, " + barheight * i + ")";
});
var bars = barGroups.selectAll('rect');
enterGroup.append('rect') //ENTER
.attr('class', 'bar')
.attr('height', barheight - 1)
.merge(bars) //UPDATE
.attr('width', function(d){
return scale(d);
})
.attr('fill', 'steelblue');
var texts = barGroups.selectAll('text');
enterGroup.append("text") //ENTER
.attr('class', 'text')
.attr("y", barheight / 2)
.attr("dy", ".35em")
.merge(texts) //UPDATE
.attr("x", function(d) { return scale(d) + 10; })
.text(function(d) { return d;});
}
Seems to work after merging the groups first, then updating the rects and texts:
https://bl.ocks.org/ckothari/699b112b6e1376779e65973bbabdced6
I have a scatter plot. Now if I click on one of the points, how can I generate a line passing through that point?
I am stuck at two places:
With the following code, why is my line now showing?
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="d3.min.js"></script>
<script>
var width = 500, height = 500;
var randomX=[], randomY=[];
for (var i=0; i<=50; i++) {
randomX[i] = Math.random()*400;
randomY[i] = Math.random()*400;}
var data = randomX.concat(randomY);
var x = d3.scale.linear()
.domain([0, d3.max(randomX)])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, d3.max(randomY)])
.range([height, 0]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
svg.selectAll("scatter-dots")
.data(randomY)
.enter().append("svg:circle")
.attr("cy", function(d) {return y(d); } )
.attr("cx", function(d,i) {return x(randomX[i]); } )
.style("fill", "brown")
.attr("r", 5)
.on("click", function(d,i) {
d3.select(this)
.append("svg:line")
.attr("x1", 300).attr("y1", 300)
.attr("x2", 50).attr("y2", 50)
.style("stroke", "steelblue")
.style("stroke-width", 3);
});
</script>
Where is the coordinates of my clicked point stored? I tried this.cx and this.cy, but none of them gave me the actual coordinates.
First, you need to append the line element to the top-level SVG or a g element, not a circle element, otherwise it won't be shown. So in your click handler, you would need to do this:
.on("click", function(d,i) {
svg.append("svg:line")
.attr("x1", 300).attr("y1", 300)
.attr("x2", 50).attr("y2", 50)
.style("stroke", "steelblue")
.style("stroke-width", 3);
});
You can get the coordinates of the click either through d3.event or the coordinates of the circle itself, i.e.
.on("click", function(d,i) {
var x = x(randomX[i]),
y = y(d);
});
or even
.on("click", function(d,i) {
var x = d3.select(this).attr("cx"),
y = d3.select(this).attr("cy");
});