d3.js creating two elements per data point - javascript

I'm wanting to add another rect element behind each bar, but I'm struggling to do this because d3.js isn't allowing me to add another element for each data point.
http://jsfiddle.net/g5hpwf0m/2/
var w = parseInt(d3.select(self).style("width")),
h = parseInt(d3.select(self).style("height")),
svg = d3.select(self)
.append("svg")
.attr("width", w)
.attr("height", h),
yScale = d3.scale.linear()
.domain([0, d3.max(dataset)])
.range([0,h]);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("fill", "green")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d){return yScale(d);});
I've tried adding this, but it doesn't do anything.
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("fill", "black")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", "100%");

You probably want to create a 'g' element and place the rects under each respective 'g' element.
var toprects = svg.append('g').attr('class','toprect');
var bottomrects = svg.append('g').attr('class','bottomrect');
bottomrects.selectAll("rect")....
toprects.selectAll("rect")....
http://jsfiddle.net/ermineia/g5hpwf0m/3/

Related

Live Bar graph with d3 in js using data from realtime firebase

I am new to javascript and have been stuck at a problem for the better part of 2 weeks. I am trying to make a bar graph that updates in real time using data from Firebase. The structure of my database is:
title:
-------child1
-------child2
-------child3
-------child4
The data to firebase is provided from a python script that is working perfectly and is updating every child of title every 10 seconds.
I made a bar graph that is updating automatically via random number generation.
//Return array of 10 random numbers
var randArray = function() {
for(var i = 0, array = new Array(); i<10; i++) {
array.push(Math.floor(Math.random()*10 + 1))
}
return array
}
var initRandArray = randArray();
var newArray;
var w = 500;
var h = 200;
var barPadding = 1;
var mAx = d3.max(initRandArray)
var yScale = d3.scale.linear()
.domain([0, mAx])
.range([0, h])
var svg = d3.select("section")
.append("svg")
.attr("width", w)
.attr("height", h)
svg.selectAll("rect")
.data(initRandArray)
.enter()
.append("rect")
.attr("x", function(d,i) {return i*(w/initRandArray.length)})
.attr("y", function(d) {return h - yScale(d)})
.attr("width", w / initRandArray.length - barPadding)
.attr("height", function(d){return yScale(d)})
.attr("fill", function(d) {
return "rgb(136, 196, " + (d * 100) + ")";
});
svg.selectAll("text")
.data(initRandArray)
.enter()
.append("text")
.text(function(d){return d})
.attr("x", function(d, i){return (i*(w/initRandArray.length) + 20)})
.attr("y", function(d) {return h - yScale(d) + 15})
.attr("font-family", "sans-serif")
.attr("fill", "white")
setInterval(function() {
newArray = randArray();
var rects = svg.selectAll("rect")
rects.data(newArray)
.enter()
.append("rect")
rects.transition()
.ease("cubic-in-out")
.duration(2000)
.attr("x", function(d,i) {return i*(w/newArray.length)})
.attr("y", function(d) {return h - yScale(d)})
.attr("width", w / newArray.length - barPadding)
.attr("height", function(d){return yScale(d)})
.attr("fill", function(d) {
return "rgb(136, 196, " + (d * 100) + ")";
});
var labels = svg.selectAll("text")
labels.data(newArray)
.enter()
.append("text")
labels.transition()
.ease("cubic-in-out")
.duration(2000)
.text(function(d){return d})
.attr("x", function(d, i){return (i*(w/newArray.length) + 20)})
.attr("y", function(d) {return h - yScale(d) + 15})
.attr("font-family", "sans-serif")
.attr("fill", "white")
}, 3000)
Live bar chart on random number
I need to update the chart using the data from firebase. I already know how to connect firebase to js using the snapshot and have already tried it to no avail.
Also, need some help with the styling of the graph.
Please if anybody knows how I can finish this(its time sensitive).
Here's the code link in jsfiddle: Live bar chart d3
Thanks

d3 axes not appearing

I'm having a problem getting the axes to actually show on my bar graph, so far without any luck as I just can't seem to wrap my head around what's wrong. Is it something to do with the scaling?
Is the axis rendering but being cut out of the svg by the bars?
<script type="text/javascript">
//Width and height
var w = 850;
var h = 650;
var barpadding = 20;
var dataset = [40, 99];
//Create SVG element
var svg = d3.select(".wrapper")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create scale functions
var x = d3.scaleBand()
.range([0, w])
.padding(0.1);
var y = d3.scaleLinear()
.range([h, 0]);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function (d, i) {
return i * (w / dataset.length);
})
.attr("y", function (d) {
return h - (d * 4);
})
.attr("width", w / dataset.length - barpadding)
.attr("height", function (d) {
return d * 4;
})
.attr("fill", "dodgerblue");
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function (d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function (d, i) {
return i * (w / dataset.length) + (w / dataset.length - barpadding) / 2;
})
.attr("y", function (d) {
return h - (d * 4) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "18px")
.attr("fill", "black");
d3.select(".axis")
.call(d3.axisBottom(x));
</script>
For showing the axis, you'll have to append a <g> element first. After that, since the axes are always generated at the origin (0,0), you'll have to translate it down and, only then, calling the axis:
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + someValue + ")")
.call(d3.axisBottom(x));
I normally provide a working demo, but this time I'll skip it, because your code has some problems:
It lacks the margins for the axis
It lacks the domains of the scales
It position the bars using magic numbers, not the scales
But, if you want to see your code with the axis 20px above the bottom, this is how it looks like: https://jsfiddle.net/qcnako3g/

d3.js transparent shape tesselations - complex subtractions

Expanding on this first example. I am interested to expand the solutions.
1 - make this more responsive - scaling wise
2 - make the subtraction more complex
3 - ensure the svg fits over the width of the banner.
d3.js - masking shapes to create transparent sectio
So here is the goal
this is the code as it is - I've given it a little clean up.
http://jsfiddle.net/NYEaX/1521/
function maskMaker(el) {
var backcolor = $(el).data("color");
var backopacity = $(el).data("opacity");
// Set the main elements for the series chart
var svgroot = d3.select($(el)[0]).append("svg");
var mask = svgroot
.append("defs")
.append("mask")
.attr("id", "myMask");
mask.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", "1200px")
.attr("height", 500)
.style("fill", "white")
.style("opacity", backopacity);
mask.append("circle")
.attr("cx", 550)
.attr("cy", 250)
.attr("r", 150);
var svg = svgroot
.attr("class", "series")
.attr("width", "1200px")
.attr("height", "500px")
.append("g")
.attr("transform", "translate(0,0)")
var rect = svg
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", "1200px")
.attr("height", 500)
.attr("mask", "url(#myMask)")
.style("fill", backcolor);
}
//var el = $(".mask"); //selector
$('[data-role="mask"]').each(function(index) {
console.log("test")
maskMaker(this);
});

d3: Elements move when scale() transform is applied

I want SVG elements to appear larger on mouseover. Applying a CSS transform seems to be a convenient way to do this, however it also translates the objects. How do I make the circles in the below example keep their original center point? I've tried applying position: absolute; to no avail.
var dataset = [0, 2345786000, 10000000000];
var svg = d3.select("body").append("svg");
var w = 500, h = 200;
var padding = 50;
svg.attr("width", w)
.attr("height", h);
// Background pattern
var patternSize = 5;
svg.append("defs")
.append("pattern")
.attr("id", "dotPattern")
.attr("patternUnits", "userSpaceOnUse")
.attr("width", patternSize)
.attr("height", patternSize)
.append("circle")
.attr("cx", patternSize / 2)
.attr("cy", patternSize / 2)
.attr("r", 2)
.style("stroke", "none")
.style("fill", "lightgrey")
.style("opacity", 0.5);
var xScale = d3.time.scale()
.domain([0, 10000000000])
.range([padding, w-padding]);
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(5);
svg.append("g")
.attr("class","axis")
.attr("transform", "translate(0," + (h-padding) + ")")
.call(xAxis);
var zoom = d3.behavior.zoom()
.on("zoom", build)
.scaleExtent([1, 20]);
zoom.x(xScale);
var clipPath = svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("x", padding)
.attr("y", 0)
.attr("width",w-2*padding)
.attr("height", h-padding);
var zoomArea = svg.append("g")
.attr("class", "zoomArea")
.style("cursor","move")
.attr("clip-path", "url(#clip)");
var zoomRect = zoomArea.append("rect")
.attr("x", padding)
.attr("y", 0)
.attr("width", w-2*padding)
.attr("height", h-padding)
.style("fill", "url(#dotPattern)")
.style("pointer-events", "all")
.style("cursor","move")
.call(zoom);
zoomArea.selectAll("circles")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d){
return xScale(d);
})
.attr("cy", h/2)
.attr("r",10)
.attr("fill","grey")
.on("mouseover", function(){
d3.select(this)
.attr("transform", "scale(1.4)")
})
.on("mouseout", function(){
d3.select(this)
.attr("transform", "scale(1)")
});
function build(){
svg.select("g.axis").call(xAxis);
d3.selectAll("circle")
.attr("cx", function(d){
return xScale(d);
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
There are two possible ways of resolving this issue.
1. To scale the circle without changing it's position, do as shown below.
translate(-centerX*(factor-1), -centerY*(factor-1)) scale(factor)
Working Fiddle 1:
var dataset = [0, 2345786000, 10000000000];
var svg = d3.select("body").append("svg");
var w = 500,
h = 200;
var padding = 50;
svg.attr("width", w)
.attr("height", h);
// Background pattern
var patternSize = 5;
svg.append("defs")
.append("pattern")
.attr("id", "dotPattern")
.attr("patternUnits", "userSpaceOnUse")
.attr("width", patternSize)
.attr("height", patternSize)
.append("circle")
.attr("cx", patternSize / 2)
.attr("cy", patternSize / 2)
.attr("r", 2)
.style("stroke", "none")
.style("fill", "lightgrey")
.style("opacity", 0.5);
var xScale = d3.time.scale()
.domain([0, 10000000000])
.range([padding, w - padding]);
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(5);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
var zoom = d3.behavior.zoom()
.on("zoom", build)
.scaleExtent([1, 20]);
zoom.x(xScale);
var clipPath = svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("x", padding)
.attr("y", 0)
.attr("width", w - 2 * padding)
.attr("height", h - padding);
var zoomArea = svg.append("g")
.attr("class", "zoomArea")
.style("cursor", "move")
.attr("clip-path", "url(#clip)");
var zoomRect = zoomArea.append("rect")
.attr("x", padding)
.attr("y", 0)
.attr("width", w - 2 * padding)
.attr("height", h - padding)
.style("fill", "url(#dotPattern)")
.style("pointer-events", "all")
.style("cursor", "move")
.call(zoom);
zoomArea.selectAll("circles")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
return xScale(d);
})
.attr("cy", h / 2)
.attr("r", 10)
.attr("fill", "grey")
.on("mouseover", function(d) {
var x = xScale(d),
y = h / 2,
factor = 2;
var tx = -x * (factor - 1),
ty = -y * (factor - 1);
d3.select(this).transition().duration(50)
.attr("transform", "translate(" + tx + "," + ty + ") scale(" + factor + ")");
})
.on("mouseleave", function(d) {
var x = xScale(d),
y = h / 2,
factor = 1;
var tx = -x * (factor - 1),
ty = -y * (factor - 1);
d3.select(this).transition().duration(50)
.attr("transform", "translate(" + tx + "," + ty + ") scale(" + factor + ")");
});
function build() {
svg.select("g.axis").call(xAxis);
d3.selectAll("circle")
.attr("cx", function(d) {
return xScale(d);
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
2. Since you are using circle, you can just increase the radius of circles easily to scale them.
Working Fiddle 2:
var dataset = [0, 2345786000, 10000000000];
var svg = d3.select("body").append("svg");
var w = 500,
h = 200;
var padding = 50;
svg.attr("width", w)
.attr("height", h);
// Background pattern
var patternSize = 5;
svg.append("defs")
.append("pattern")
.attr("id", "dotPattern")
.attr("patternUnits", "userSpaceOnUse")
.attr("width", patternSize)
.attr("height", patternSize)
.append("circle")
.attr("cx", patternSize / 2)
.attr("cy", patternSize / 2)
.attr("r", 2)
.style("stroke", "none")
.style("fill", "lightgrey")
.style("opacity", 0.5);
var xScale = d3.time.scale()
.domain([0, 10000000000])
.range([padding, w - padding]);
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(5);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
var zoom = d3.behavior.zoom()
.on("zoom", build)
.scaleExtent([1, 20]);
zoom.x(xScale);
var clipPath = svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("x", padding)
.attr("y", 0)
.attr("width", w - 2 * padding)
.attr("height", h - padding);
var zoomArea = svg.append("g")
.attr("class", "zoomArea")
.style("cursor", "move")
.attr("clip-path", "url(#clip)");
var zoomRect = zoomArea.append("rect")
.attr("x", padding)
.attr("y", 0)
.attr("width", w - 2 * padding)
.attr("height", h - padding)
.style("fill", "url(#dotPattern)")
.style("pointer-events", "all")
.style("cursor", "move")
.call(zoom);
zoomArea.selectAll("circles")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) {
return xScale(d);
})
.attr("cy", h / 2)
.attr("r", 10)
.attr("fill", "grey")
.on("mouseover", function() {
d3.select(this).transition().duration(50).attr("r", 20);
})
.on("mouseleave", function() {
d3.select(this).transition().duration(50).attr("r", 10);
});
function build() {
svg.select("g.axis").call(xAxis);
d3.selectAll("circle")
.attr("cx", function(d) {
return xScale(d);
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Access x property on svg element in d3

I'm trying to implement a transform wherein an element moves a couple of pixels to the left by several pixels when a user mouses over it. How can I access the x property of a bar so I can pass in a relative position?
Here's my code; it's pretty standard except that I don't have an axis on the bar chart.
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
var tip = d3.tip()
.attr('class','d3-tip')
.html(function(d, i) {
return "<span style='color:red'>" + d.Word +"</span>";
});
svg.selectAll("rect")
.data(words)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i*(w/dataset.length);
})
.attr("y", function(d){
return (h-(800)
);
})
.attr("width", 40)
.attr("class", "rectangle")
.attr("id", function(d, i){return "rect"+i})
.attr("height", function(d, i){
// var barheight = d.Dispersion*100
return "200px"
})
.on("mouseover", tip.show)
.on("mouseout", tip.hide);
svg.call(tip);
$('.rectangle').mouseover(function () {
var rect = d3.select("#"+this.id)
rect.transition()
.duration(500)
.attr("width", 58)
.duration(500)
.attr("height", 220+"px")
.style("fill", function(d, i) {return d.color});
.attr("x", 50) //this goes to a particular position in the parent node
});

Categories

Resources