d3 lines between dots not working - javascript

I have made a scatter plot using d3 and want to connect the dots with lines, I have tried using what people have written online to connect the lines but it does not seem to be working.
function makeGraph(sampleData){
console.log(sampleData);
var vis = d3.select("#svgVisualize");
yMax = d3.max(sampleData, function (point) {return point.y;});
//step 1 : scale the data
xRange = d3.scale.ordinal().domain(sampleData.map(function (d) { return d.x; })).rangePoints([0, 700]);
yRange = d3.scale.linear().range([400, 40]).domain([0, yMax]);
//step 2: scale the axis
xAxis = d3.svg.axis().scale(xRange);
yAxis = d3.svg.axis().scale(yRange).orient("left");
//Step3: append the x and y axis
vis.append('svg:g')
.call(xAxis)
.attr("transform", "translate(90,400)")
.append("text")
.text("Build Model")
.attr("y", 70)
.attr("x", 150);
vis.append('svg:g')
.call(yAxis)
.attr("transform", "translate(90,0)")
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -80)
.attr("x", -130)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Users");
var circles = vis.selectAll("circle").data(sampleData);
circles
.enter()
.insert("circle")
.attr("cx", function (d) {return xRange(d.x);})
.attr("cy", function (d) { return yRange(d.y); })
.attr("r", 4)
.attr("transform", "translate(90,0)")
.style("fill", "blue");
var lineFunction = vis.line()
.x(function (d) {
return d.x;
})
.y(function (d) {
return d.y;
})
.interpolate("linear");
vis.append("path")
.attr("d", lineFunction(sampleData))
.style("stroke-width", 0.5)
.style("stroke", "rgb(6,120,155)")
.style("fill", "none")
.on("mouseover", function () {
d3.select(this)
.style("stroke", "orange");
})
.on("mouseout", function () {
d3.select(this)
.style("stroke", "rgb(6,120,155)");
});
}
If anyone could help that would be great, I'm still new to d3

Your example is working fine, I had to do the following
Change the line that creates a path generator to d3.svg.line (just like Gerardo's answer)
Create a group for your circles and the path so that you don't have to add .attr("transform", "translate(90,0)") to both of them
Use a data join for the path (although it's not required)
function makeGraph(sampleData) {
var svg = d3.select('#svgVisualize')
yMax = d3.max(sampleData, function(point) {
return point.y;
});
xRange = d3.scale.ordinal().domain(sampleData.map(function(d) {
return d.x;
})).rangePoints([0, 700]);
yRange = d3.scale.linear().range([400, 40]).domain([0, yMax]);
//step 2: scale the axis
xAxis = d3.svg.axis().scale(xRange);
yAxis = d3.svg.axis().scale(yRange).orient("left");
//Step3: append the x and y axis
svg.append('svg:g')
.call(xAxis)
.attr("transform", "translate(90,400)")
.append("text")
.text("Build Model")
.attr("y", 70)
.attr("x", 150);
svg.append('svg:g')
.call(yAxis)
.attr("transform", "translate(90,0)")
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -80)
.attr("x", -130)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Users");
// data
var g = svg.append('g')
.attr('class', 'data')
.attr("transform", "translate(90,0)")
var circles = g.selectAll("circle").data(sampleData);
circles
.enter()
.insert("circle")
.attr("cx", function(d) {
return xRange(d.x);
})
.attr("cy", function(d) {
return yRange(d.y);
})
.attr("r", 4)
.style("fill", "blue");
var lineFunction = d3.svg.line()
.x(function(d) { return xRange(d.x); })
.y(function(d) { return yRange(d.y); })
.interpolate("linear");
var path = g.selectAll('path').data([sampleData])
.enter()
.append('path')
.attr("d", lineFunction)
.style("stroke-width", 0.5)
.style("stroke", "rgb(6,120,155)")
.style("fill", "none")
.on("mouseover", function() {
d3.select(this)
.style("stroke", "orange");
})
.on("mouseout", function() {
d3.select(this)
.style("stroke", "rgb(6,120,155)");
});
}
makeGraph([
{x: 0, y: 100},
{x: 100, y: 100},
{x: 200, y: 200},
{x: 300, y: 100}
])
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg id="svgVisualize" width="900" height="500" style="position: relative; left: 2%;"></svg>

The line function has to be like this:
var lineFunction = d3.svg.line()
.x(function(d) { return xRange(d.x); })
.y(function(d) { return yRange(d.y); })
.interpolate("linear");

Related

Add Tooltip on Scatter points, error is generated for D3.js Version 4

My question is- I have generated a scatter plot using D3 version 4. Now, I need to add tooltip to points, on mouseover. But, I am getting an error message- "setAttribute is not a function" Can Someone provide me a clue for the same, and check if the function declaration is right?
https://jsfiddle.net/kunal16/be37wmaj/
var width = 700;
var height = 700;
var padding = 70;
var myData = [12, 15, 20, 9, 17, 25, 30];
var errData = [6, 7.5, 10, 4.5, 8.5, 12.5, 15];
var svg = d3.select("body").
append("svg")
.attr("width", width)
.attr("height", height);
var yScale = d3.scaleLinear().domain([0, d3.max(myData)]).range([height/2, 0]);
var xScale = d3.scaleLinear().domain([0, d3.max(myData)]).range([0, width - 200]);
var y_ErScale = d3.scaleLinear().domain([0, d3.max(errData)]).range([height/2, 0]);
var x_ErScale = d3.scaleLinear().domain([0, d3.max(errData)]).range([0, width - 200]);
// var div = d3.select("body").append("svg")
// .attr("class", "tooltip")
// .style("opacity", 0);
var eBar = d3.select("body").append("svg");
//var x_min =
var x_axis = d3.axisBottom()
.scale(xScale);
var y_axis = d3.axisLeft()
.scale(yScale);
svg.append("g")
.attr("transform", "translate(50, 10)")
.call(y_axis);
var xAxisTranslate = height/2 + 10;
svg.append("g")
.attr("transform", "translate(50, " + xAxisTranslate +")")
.call(x_axis);
svg.append("g")
.selectAll("scatter-dots")
.data(myData)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return xScale(myData[i]); } )
.attr("cy", function (d) { return yScale(d); } )
.attr("r", 3)
.style("opacity", 0.8);
// var errorBar = eBar.append("path")
// .attr("d", yScale(errData))
// .attr("stroke", "red")
// .attr("stroke-width", 1.5);
// svg.append("g")
// .selectAll("error-bars")
// .data(errData)
// .enter().append("svg:path")
// .attr("cx", function (d,i) { return x_ErScale(errData[i]); } )
// .attr("cy", function (d) { return y_ErScale(d); } )
// .attr("stroke", "red")
// .attr("stroke-width", 1.5);
svg.append("g")
.selectAll("line")
.data(errData)
.enter()
.append("line")
.attr("class", "error-line")
.attr("x1", function(d) {
return x_ErScale(d);
})
.attr("y1", function(d) {
return y_ErScale(d) + 30;
})
.attr("x2", function(d) {
return x_ErScale(d);
})
.attr("y2", function(d) {
return y_ErScale(d) + 2;
});
svg.append("g").selectAll("line")
.data(errData).enter()
.append("line")
.attr("class", "error-cap")
.attr("x1", function(d) {
return x_ErScale(d) - 20;
})
.attr("y1", function(d) {
return y_ErScale(d) - 30;
})
.attr("x2", function(d) {
return x_ErScale(d) + 20;
})
.attr("y2", function(d) {
return y_ErScale(d) - 30;
});
svg.append("g")
.selectAll("line")
.data(errData)
.enter()
.append("line")
.attr("class", "error-line")
.attr("x1", function(d) {
return x_ErScale(d);
})
.attr("y1", function(d) {
return y_ErScale(d) - 30;
})
.attr("x2", function(d) {
return x_ErScale(d);
})
.attr("y2", function(d) {
return y_ErScale(d) - 2;
});
// Add Error Bottom Cap
svg.append("g").selectAll("line")
.data(errData).enter()
.append("line")
.attr("class", "error-cap")
.attr("x1", function(d) {
return x_ErScale(d) - 20;
})
.attr("y1", function(d) {
return y_ErScale(d) + 30;
})
.attr("x2", function(d) {
return x_ErScale(d) + 20;
})
.attr("y2", function(d) {
return y_ErScale(d) + 30;
});
// console.log(svg.append("g").selectAll("scatter-dots"));
var div = svg.append("g").selectAll("scatter-dots")
.data(myData)
.enter()
// .append("circle")
.attr("class", "tooltip")
.style("opacity", 0)
.on("mouseover", function(d)
{
div
.transition()
.duration(200)
.html(myData)
.style("opacity", 0.8);
})
.on("mouseout", function(d)
{
div
.transition()
.duration(500)
.style("opacity", 0);
});
Please refer the above fiddle.Thanks!
Adding divs to each circle is unneccessary once you have joined the data to create the circles. You can put listeners on the circle with mouseover and mouseout functions.
https://jsfiddle.net/xqqfq9hf/
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
svg.append("g")
.selectAll("scatter-dots")
.data(myData)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return xScale(myData[i]); } )
.attr("cy", function (d) { return yScale(d); } )
.attr("r", 3)
.style("opacity", 0.8)
.on("mouseover", function(d) {
tooltip.transition()
.duration(200)
.style("opacity", .9);
tooltip.html(d)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
});

Total height of Stacked Bar on tip of every rectangle in stacked Bar Chart using d3

I drawn a stackedbar Chart in which now I trying to place the Total value(I mean the yaxis value) on tip of the every rectangle. I have coded to fetch the details but here the problem is I am getting Every Layer value on tip of every layer but i need to show only the last layer value.
the problem is shown in below fig's.
My code is Shown below
var fData =
[{"orders":"A","Total_Orders":76,"A_Lines":123,"B_Lines":0,"C_Lines":0,"D_Lines":0,"Total_Lines":123,"Total_Units":3267},
{"orders":"B","Total_Orders":68,"A_Lines":0,"B_Lines":107,"C_Lines":0,"D_Lines":0,"Total_Lines":107,"Total_Units":3115},
{"orders":"C","Total_Orders":81,"A_Lines":0,"B_Lines":0,"C_Lines":123,"D_Lines":0,"Total_Lines":123,"Total_Units":3690},
{"orders":"D","Total_Orders":113,"A_Lines":0,"B_Lines":0,"C_Lines":0,"D_Lines":203,"Total_Lines":203,"Total_Units":7863},
{"orders":"AB","Total_Orders":62,"A_Lines":70,"B_Lines":76,"C_Lines":0,"D_Lines":0,"Total_Lines":146,"Total_Units":1739},
{"orders":"AC","Total_Orders":64,"A_Lines":77,"B_Lines":0,"C_Lines":79,"D_Lines":0,"Total_Lines":156,"Total_Units":2027},
{"orders":"AD","Total_Orders":100,"A_Lines":127,"B_Lines":0,"C_Lines":0,"D_Lines":144,"Total_Lines":271,"Total_Units":6467},
{"orders":"BC","Total_Orders":64,"A_Lines":0,"B_Lines":80,"C_Lines":84,"D_Lines":0,"Total_Lines":164,"Total_Units":1845},
{"orders":"BD","Total_Orders":91,"A_Lines":0,"B_Lines":108,"C_Lines":0,"D_Lines":135,"Total_Lines":243,"Total_Units":4061},
{"orders":"CD","Total_Orders":111,"A_Lines":0,"B_Lines":0,"C_Lines":132,"D_Lines":147,"Total_Lines":279,"Total_Units":5011},
{"orders":"ABC","Total_Orders":45,"A_Lines":58,"B_Lines":63,"C_Lines":55,"D_Lines":0,"Total_Lines":176,"Total_Units":1245},
{"orders":"ABD","Total_Orders":69,"A_Lines":105,"B_Lines":87,"C_Lines":0,"D_Lines":116,"Total_Lines":308,"Total_Units":4538},
{"orders":"ACD","Total_Orders":66,"A_Lines":91,"B_Lines":0,"C_Lines":88,"D_Lines":132,"Total_Lines":311,"Total_Units":4446},{
{"orders":"BCD","Total_Orders":68,"A_Lines":0,"B_Lines":84,"C_Lines":95,"D_Lines":111,"Total_Lines":290,"Total_Units":4187},
{"orders":"ABCD","Total_Orders":56,"A_Lines":96,"B_Lines":90,"C_Lines":93,"D_Lines":143,"Total_Lines":422,"Total_Units":6331}]
var headers = ["A_Lines", "B_Lines", "C_Lines", "D_Lines"];
var colors = ["#9999CC", "#F7A35C", "#99CC99", "#CCCC99"];
var colorScale = d3.scale.ordinal()
.domain(headers)
.range(colors);
var layers = d3.layout.stack()(headers.map(function (count) {
return fData.map(function (d, i) {
// alert(d);
return { x: d.ORDER_TYPE, y: +d[count], color: colorScale(count) };
});
}));
//StackedBar Rectangle Max
var yStackMax = d3.max(layers, function (layer) { return d3.max(layer, function (d) { return d.y0 + d.y; }); });
// Set x, y and colors
var xScale = d3.scale.ordinal()
.domain(layers[0].map(function (d) { return d.x; }))
.rangeRoundBands([25, width], .08);
var y = d3.scale.linear()
.domain([0, yStackMax])
.range([height, 0]);
// var color = d3.scale.ordinal()
//.domain(headers)
// .range(["#9999CC", "#F7A35C", "#99CC99", "#CCCC99"]);
// Define and draw axes
var xAxis = d3.svg.axis()
.scale(xScale)
.tickSize(1)
.tickPadding(6)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function (d, i) { return colorScale(i); });
var rect = layer.selectAll("rect")
.data(function (d) { return d; })
.enter().append("rect")
.attr("x", function (d) { return xScale(d.x); })
.attr("y", height)
.attr("width", xScale.rangeBand())
.attr("height", 0)
.attr("class", function (d) {
return "rect bordered " + "color-" + d.color.substring(1);
});
layer.selectAll("text.rect")
.data(function (layer) { return layer; })
.enter().append("text")
.attr("text-anchor", "middle")
.attr("x", function (d) { return xScale(d.x) + xScale.rangeBand() / 2; })
.attr("y", function (d) { return y(d.y + d.y0) - 3; })
.text(function (d) { return d.y + d.y0; })
.style("fill", "4682b4");
//********** AXES ************
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text").style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", function (d) {
return "rotate(-45)"
});
svg.attr("class", "x axis")
.append("text")
.attr("text-anchor", "end") // this makes it easy to centre the text as the transform is applied to the anchor
.attr("transform", "translate(" + (width / 2) + "," + (height + 60) + ")") // centre below axis
.text("Order Velocity Group");
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(20,0)")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr({ "x": -75, "y": -70 })
.attr("dy", ".75em")
.style("text-anchor", "end")
.text("No. Of Lines");
//********** LEGEND ************
var legend = svg.selectAll(".legend")
.data(headers.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(" + i * (-100) + "," + (height + 50) + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
//.style("fill", color);
.style("fill", function (d, i) { return colors[i]; })
.on("mouseover", function (d, i) {
svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "blue");
})
.on("mouseout", function (d, i) {
svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "white");
});
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) { return d; });
transitionStacked();
function transitionStacked() {
y.domain([0, yStackMax]);
rect.transition()
.duration(500)
.delay(function (d, i) { return i * 10; })
.attr("y", function (d) { return y(d.y0 + d.y); })
.attr("height", function (d) { return y(d.y0) - y(d.y0 + d.y); })
.transition()
.attr("x", function (d) { return xScale(d.x); })
.attr("width", xScale.rangeBand());
rect.on('mouseover', tip.show)
.on('mouseout', tip.hide)
};
can anyone help me.
Here is what you need: First, we'll set fData as the data for the texts:
layer.selectAll("text.rect")
.data(fData)
.enter()
.append("text")
But, as this dataset doesn't have the correct yScale value, we'll have to extract it using a filter:
.attr("y", function (d) {
var filtered = fData.filter(function(e){
return e.Total_Units == d.Total_Units
});
return y(filtered[0].Total_Lines) - 3;
})
All together:
layer.selectAll("text.rect")
.data(fData)
.enter().append("text")
.attr("text-anchor", "middle")
.attr("x", function(d) {
return xScale(d.orders) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
var filtered = fData.filter(function(e) {
return e.Total_Units == d.Total_Units
});
return y(filtered[0].Total_Lines) - 3;
})
.text(function(d) {
return d.Total_Units
})
.style("fill", "4682b4");
Here is your fiddle: https://jsfiddle.net/wnwb6meh/

Data not being redrawn after being filtered on d3 bar chart

I've been trying to add a filter to a bar chart. The bar is removed when I click on the legend, but when I try to reactivate the bar is not being redrawn.
Here is a plnk;
http://plnkr.co/edit/GZtErHGdq8GbM2ZawQSD?p=preview
I can't seem to work out the issue - if anyone could lend a hand?
Thanks
JS code;
// load the data
d3.json("data.json", function(error, data) {
var group = [];
function updateData() {
group = [];
var organization = data.organizations.indexOf("Org1");
var dateS = $("#selectMonth").text()
for (var country = 0; country < data.countries.length; country++) {
var date = data.dates.indexOf(dateS);
group.push({
question: data.organizations[organization],
label: data.countries[country],
value: data.values[organization][country][date]
});
}
}
function draw(create) {
updateData();
x.domain(group.map(function(d) {
return d.label;
}));
y.domain([0, 100]);
// add axis
// Add bar chart
var bar = svg.selectAll("rect")
.data(group);
if (create) {
bar
.enter().append("rect")
.attr('x', function(d) {
return x(d.label);
})
.attr('y', function(d) {
return y(d.value);
})
.attr('width', x.rangeBand())
.attr('height', function(d) {
return height - y(d.value);
});
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 5)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Value");
}
bar
.transition()
.duration(750)
.attr("y", function(d) {
return y(d.value);
})
.attr("height", function(d) {
return height - y(d.value);
});
// Existing code to draw y-axis:
var legendGroups = d3.select("#legend")
.selectAll(".legendGroup")
.data(group, function(d) {
return d.label; // always try and use a key function to uniquely identify
});
var enterGroups = legendGroups
.enter()
.append("g")
.attr("class", "legendGroup");
legendGroups
.exit()
.remove();
legendGroups
.attr("transform", function(d, i) {
return "translate(10," + (10 + i * 15) + ")"; // position the whole group
});
enterGroups.append("text")
.text(function(d) {
return d.label;
})
.attr("x", 15)
.attr("y", 10);
enterGroups
.append("rect")
.attr("width", 10)
.attr("height", 10)
.attr("fill", function(d) {
return "#bfe9bc";
})
.attr("class", function(d, i) {
return "legendcheckbox " + d.label.replace(/\s|\(|\)|\'|\,|\.+/g, '')
})
.on("click", function(d) {
d.active = !d.active;
d3.select(this).attr("fill", function(d) {
if (d3.select(this).attr("fill") == "#cccccc") {
return "#bfe9bc";
} else {
return "#cccccc";
}
})
var result = group.filter(function(d) {
return $("." + d.label.replace(/\s|\(|\)|\'|\,+/g, '')).attr("fill") != "#cccccc"
})
x.domain(result.map(function(d) {
return d.label;
}));
bar
.select(".x.axis")
.transition()
.call(xAxis);
bar
.data(result, function(d) {
return d.label.replace(/\s|\(|\)|\'|\,|\.+/g, '')
})
.enter()
.append("rect")
.attr("class", "bar")
bar
.transition()
.attr("x", function(d) {
return x(d.label);
})
.attr("width", x.rangeBand())
.attr("y", function(d) {
return y(d.value);
})
.attr("height", function(d) {
return height - y(d.value);
});
bar
.data(result, function(d) {
return d.label.replace(/\s|\(|\)|\'|\,|\.+/g, '')
})
.exit()
.remove()
});
}
The bar disappear because you totally remove it with
.remove()
What you can do is hide the element when not selected like that :
d3.selectAll('.graph').selectAll("rect").attr("visibility", function(e) {
return e.active ? "hidden" : "";
})
See http://plnkr.co/edit/2UWaZOsffkw1vkdIJuSA?p=preview

Uncaught TypeError: Cannot read property 'mydata' of undefined

Data being inputted correctly, but shown as undefined when logged:
d3.json('linedata.00.json', function(error, data){
console.log(data)
Error shows up on this line:
data.mydata.forEach(function (kv) {
var labelName = kv.label;
var colorName = kv.color
kv.values.forEach(function (d) {
d.id = d.id;
d.color = colorName;
d.val = +d.val;
d.label = labelName;
});
});
JSON Code as follows:
{
"mydata":[
{
"id":"line01",
"color":"#de6868",
"label":"internal",
"values":[
{"week":"Week 1","val":37},
{"week":"Week 2","val":38},
{"week":"Week 3","val":33},
{"week":"Week 4","val":32},
{"week":"Week 5","val":40},
{"week":"Week 6","val":27},
{"week":"Week 7","val":30},
{"week":"Week 8","val":37},
{"week":"Week 9","val":42},
{"week":"Week 10","val":36},
{"week":"Week 11","val":35},
{"week":"Week 12","val":37},
{"week":"Week 13","val":33}
]
},
The question is. Why am I getting the error when everything is (seemingly) in the right place and how do I fix it?
Callback in it's entirety:
d3.json('linedata.00.json', function(error, data){
console.log(data)
data.mydata.forEach(function (kv) {
var labelName = kv.label;
var colorName = kv.color
kv.values.forEach(function (d) {
d.id = d.id;
d.color = colorName;
d.val = +d.val;
d.label = labelName;
});
});
color.domain(data.mydata.map(function (d) { return d.label; }));
myColor = function(d){return d.color};
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<span style='color:red'>" + d3.format("$,")(d.val) + "</span>";
})
svg.call(tip);
var dataNest = d3.nest()
.key(function(d) {return d.label;})
.entries(data.mydata);
function make_y_axis() { // function for the y grid2 lines
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
}
console.log(yAxis.ticks());
var minY = d3.min(data.mydata, function (kv) { return d3.min(kv.values, function (d) { return d.val; }) });
var maxY = d3.max(data.mydata, function (kv) { return d3.max(kv.values, function (d) {return d.val; }) });
var maxX = d3.max(data.mydata, function (kv){return d3.max(kv.values, function(d){ return d.week + 1;});});
console.log(maxX);
var padding = width/(data.mydata[0].values.length + 1)/2;
x.domain(data.mydata[0].values.map(function (d) { return d.week; })).rangePoints([padding, width-padding]);
y.domain([0,(1.2 * maxY)]);
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");
svg.append("g") // Draw the y grid2 lines
.attr("class", "grid2")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat("")
);
svg.selectAll(".grid2")
.selectAll(".tick")
.append("rect")
.attr("width", width)
.attr("height", height / (yAxis.ticks()[0]-1) -3)
.attr("class", function(d, i) {
return ((i) % 2) == 1 ? "zebraGrey" : "zebraNone";
})
.attr("stroke", "none");
var city = svg.selectAll(".branch")
.data(data.mydata)
.enter().append("g")
.attr("class", "branch");
city.append("path")
.attr("class", "line")
.attr("id", function(d){return d.id})
.attr("data-legend",function(d){return d.label;})
.attr("d", function (d) {
return line(d.values);
})
.style("stroke", myColor)
.style("fill", "none")
.style("stroke-width", 3);
svg.selectAll("g.dot")
.data(data.mydata)
.enter().append("g")
.attr("class", "dot")
.selectAll("circle")
.data(function(d) {return d.values; })
.enter().append("circle")
// .style("stroke", function (d){return d.color;})
.attr("r", 2)
.attr("cx", function(d,i) { return x(d.week); })
.attr("cy", function(d,i) { return y(d.val); })
.style("stroke", myColor)
.style("fill", myColor)
.style("stroke-width", 3)
// Tooltip stuff after this
.on("mouseover", tip.show)
.on("mouseout", tip.hide);
// add legend
var legend = svg.append("g")
.attr("class", "legend")
.attr("height", 100)
.attr("width", 100)
.attr('transform', 'translate('+ -1 * .37 * width + ',' + height +')');
legend.selectAll('rect')
.data(data.mydata)
.enter()
.append("rect")
.attr("x", function(d, i){return i * 150 + 480})
.attr("y", 40)
.attr("width", 10)
.attr("height", 10)
.style("fill", myColor)
.style("stroke", "none");
legend.selectAll('text')
.data(data.mydata)
.enter()
.append("text")
.attr("class", "legText")
.attr("x", function(d, i){ return i * 150 + 500;})
.attr("y", 50)
.style("fill", myColor)
.style("stroke", "none")
.text(function(d){return d.label});
});
Thanks everyone for looking into this. The code was right, I had two misplaced comas in the JSON itself that were causing the troubles. Thanks though for the concern.

d3 graph with limited zoom

I have implemented a d3 line graph which reads data from a CSV file, and then plots multiple lines which react to mouseover events. It works fine with pan and zoom using the following code (sorry that it is so long and slightly untidy but I felt it best to display the full code):
d3.csv("ijisb.csv", function(error, data) {
var margin = {top: 50, right: 120, bottom: 50, left: 70},
width = 1200 - margin.left - margin.right,
height = 800 - margin.top - margin.bottom;
var parseDate = d3.time.format("%m%d").parse;
var color = d3.scale.category20();
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
data.forEach(function(d) {
d.date = parseDate(d.date);
});
var sources = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, temperature: +d[name]};
})
};
});
var x = d3.time.scale()
.range([0, width])
.domain([
d3.min(data, function(d) { return d.date; }),
d3.max(data, function(d) { return d.date; })
]);
var y = d3.scale.linear()
.range([height, 0])
.domain([
0,
d3.max(sources, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); })
]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(12)
.tickFormat(d3.time.format("%b %d"));
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
var line = d3.svg.line()
.defined(function(d) { return d.temperature >= 0; })
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.temperature); });
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 8])
.on("zoom", zoomed);
var svg = d3.select("body").append("svg")
.attr("width", "100%")
.attr("height", "100%")
.attr("viewBox", "0 0 1200 800")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
var rect = svg.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("class", "plot");
var make_x_axis = function () {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(12)
.tickFormat(d3.time.format("%b %d"));
};
var make_y_axis = function () {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
};
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat(""));
svg.append("g")
.attr("class", "y grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat(""));
var source = svg.selectAll(".source")
.data(sources)
.enter().append("g")
.attr("class", "source");
var clip = svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.append("text");
source.append("path")
.data(sources)
.attr("class", "line")
.attr("clip-path", "url(#clip)")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) {return color(d.name);})
.style("opacity", 0.8)
.on("mouseover", function(d){
d3.select(this)
.style("stroke",function(d) {return color(d.name);})
.style("opacity", 1.0)
.style("stroke-width", 2.5);
this.parentNode.parentNode.appendChild(this.parentNode);
d3.select('#text-' + d.name)
.style("fill",function(d) {return color(d.name);})
.style("font-weight", 700);
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(250)
.style("stroke", function(d) {return color(d.name);})
.style("stroke-width", 1.5)
.style("opacity", 0.8);
d3.select('#text-' + d.name)
.transition()
.duration(250)
.style("fill", function(d) {return color(d.name);})
.style("font-weight", 400);
})
.attr("id", function(d, i) { return "path-" + d.name; });
source.append("text")
.datum(function(d) { return {name: d.name}; })
.attr("x", function(d, i) { return width+10; })
.attr("y", function(d, i) { return (i*(height/16)); })
.style("fill", function(d) {return color(d.name);})
.on("mouseover", function(d){
d3.select('#path-' + d.name)
.style("stroke",function(d) {return color(d.name);})
.style("opacity", 1.0)
.style("stroke-width", 2.5);
this.parentNode.parentNode.appendChild(this.parentNode);
d3.select(this)
.style("fill",function(d) {return color(d.name);})
.style("font-weight", 700);
})
.on("mouseout", function(d) {
d3.select('#path-' + d.name)
.transition()
.duration(250)
.style("stroke", function(d) {return color(d.name);})
.style("stroke-width", 1.5)
.style("opacity", 0.8);
d3.select(this)
.transition()
.duration(250)
.style("fill", function(d) {return color(d.name);})
.style("font-weight", 400);
})
.text(function(d) { return d.name; })
.attr("font-family","sans-serif")
.attr("font-size","14px")
.attr("id", function(d, i) { return "text-" + d.name; }
);
var minT = new Date('01/01/1900'), maxT = new Date('01/01/2002'), w = $(window).width();
function zoomed() {
d3.event.translate;
d3.event.scale;
svg.select(".x.axis")
.call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.select(".x.grid")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat(""));
svg.select(".y.grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat(""));
source.select(".line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) {return color(d.name);});
}
});
The problem I have is that I want to limit the panning and zooming so that it is not possible for the graph to be zoomed or panned out offscreen. I can do this by setting the scaleExtent on the zoom (which is implemented in the above example) and changing the zoomed function to:
function zoomed() {
var t = zoom.translate(),
tx = t[0];
ty = t[1];
tx = Math.min(tx, 0);
zoom.translate([tx, ty]);
d3.event.translate;
d3.event.scale;
svg.select(".x.axis")
.call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.select(".x.grid")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat(""));
svg.select(".y.grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat(""));
source.select(".line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) {return color(d.name);});
}
This limits the x-axis minimum to zero. However hard I try however, I cannot limit the maximum value of the x-axis, which means the graph can still pan too far to the right.
Any help? I hope this makes sense!
Nick
Thanks for the help, I did it by the following code in the end:
var t = zoom.translate(),
s = zoom.scale();
tx = Math.min(0, Math.max(width * (1 - s), t[0]));
ty = Math.min(0, Math.max(height * (1 - s), t[1]));
zoom.translate([tx, ty]);
The difficulty was in bounding the graph at various zoom levels, which this now solves. The d3.event.translate and d3.event.scale statements were also unnecessary, and should have been removed.
You can simply check the value manually and reset it if it is too high:
if(tx > threshold) { tx = threshold; }
Also, the statements
d3.event.translate;
d3.event.scale;
in your code have no effect.

Categories