I have a graph for which I need a reference line everywhere the mouse-cursor is inside this graph. And this reference line will follow the mouse movements inside the graph.
But this doesn't seems to work fine. It works only on the axis and the ticks (.axis lines) of the axis. On debugging, I found that mouse event works fine when applied over SVG but not on the group, why so ?
Here is my code :
test.html
<html>
<head>
<script src="jquery.js">
</script>
<script src="d3.v2.js">
</script>
<script src="retest.js">
</script>
<style type="text/css">
.g_main {
cursor:pointer;
}
.axis path, .axis line {
stroke: #DBDBDB;
/*shape-rendering: crispEdges;
*/
}
.y g:first-child text {
display:none;
}
.y g:first-child line {
stroke: #989898 ;
stroke-width: 2.5px;
}
/*.x g:first-child line {
stroke: black ;
stroke-width: 2.5px;
}
*/
.y path {
stroke: #989898 ;
stroke-width: 2.5px;
}
</style>
</head>
<body>
<center>
<button id="reload" onclick="loadViz();">
load Graph
</button>
<div id="viz" class="viz">
</div>
</center>
<script>
loadViz();
</script>
</body>
</html>
retest.js
var series,
classifications,
minVal,
maxVal,
svgW = 600,
svgH = 600,
//w = 1200,
//h = 1200,
vizPadding = {
top: 120,
right: 30,
bottom: 120,
left: 50
},
yAxMin_PA = 0,
yAxMax_PA = 50,
xAxMin_PA = 2002,
xAxMax_PA = 2008,
areaStrokeColors = ['#FF6600', '#3366FF', '#B8860B', '#458B00', 'white'];
var loadViz = function () {
color = d3.scale.category10();
data = {
"lines": [{
"line": [{
"X": 2002,
"Y": 42
}, {
"X": 2003,
"Y": 45
},
{
"X": 2005,
"Y": 47
},
{
"X": 2007,
"Y": 41
}
]
}, {
"line": [{
"X": 2003,
"Y": 33
}, {
"X": 2005,
"Y": 38
}, {
"Y": 36,
"X": 2008
}
]
}, {
"line": [{
"X": 2004,
"Y": 13
}, {
"X": 2005,
"Y": 19
}, {
"X": 2008,
"Y": 21
}
]
}, {
"line": [{
"X": 2003,
"Y": 20
}, {
"X": 2005,
"Y": 27
}, {
"X": 2008,
"Y": 29
}
]
}
]
};
$("#viz").html("");
buildBase();
//setScales();
};
var buildBase = function () {
margin = {
top: 80,
right: 120,
bottom: 40,
left: 40
},
width = 960 - margin.left - margin.right,
height = 550 - margin.top - margin.bottom;
t2 = height + margin.top + margin.bottom;
x = d3.scale.linear()
.domain([xAxMin_PA, xAxMax_PA])
.range([0, width]);
y = d3.scale.linear()
.domain([yAxMin_PA, yAxMax_PA])
.range([height, 0]);
tickSizeToApplyX = 5;
tickSizeToApplyY = 10;
// Function to draw X-axis
xAxis = d3.svg.axis()
.scale(x)
.ticks(tickSizeToApplyX)
.tickSize(-height, 0, 0)
//.tickSize(10)
.orient("bottom")
.tickPadding(5);
// Function to draw Y-axis
yAxis = d3.svg.axis()
.scale(y)
.ticks(tickSizeToApplyY)
.tickSize(-width, 0, 0)
//.tickSize(0)
.orient("left")
.tickPadding(5);
// Define the line
var valueline = d3.svg.line()
.x(function (d) { /*console.log(d.X);*/
return x(d.X);
})
.y(function (d) { /*console.log(d.Y);*/
return y(d.Y);
});
// Define the line
var referline = d3.svg.line()
.x(function (dx) { /*console.log(d.X);*/
return dx;
})
.y(function (dy) { /*console.log(d.Y);*/
return dy;
});
// Append SVG into the html
var viz = d3.select("#viz")
.append("svg")
.attr("width", width + margin.left + margin.right + 10)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("class", "g_main")
.attr("transform", "translate(" + margin.left + "," + ((margin.top) - 30) + ")");
viz.on("mousemove", function () {
cx = d3.mouse(this)[0];
cy = d3.mouse(this)[1];
console.log("xx=>" + cx + "yy=>" + cy);
redrawline(cx, cy);
})
.on("mouseover", function () {
d3.selectAll('.line_over').style("display", "block");
})
.on("mouseout", function () {
d3.selectAll('.line_over').style("display", "none");
});
//console.log(this);
viz.append("line")
//d3.select("svg").append("line")
.attr("class", 'line_over')
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", x(xAxMax_PA))
.attr("y2", 0)
.style("stroke", "gray")
.attr("stroke-dasharray", ("5,5"))
.style("stroke-width", "1.5")
.style("display", "none");
// Draw X-axis
viz.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Draw Y-axis
viz.append("g")
.attr("class", function (d, i) {
return "y axis"
})
.call(yAxis);
function redrawline(cx, cy) {
d3.selectAll('.line_over')
.attr("x1", 0)
.attr("y1", cy)
.attr("x2", x(xAxMax_PA))
.attr("y2", cy)
.style("display", "block");
}
};
The g element is just an empty container which cannot capture click events (see documentation for pointer-events property for details).
However, mouse events do bubble up to it. Hence, the effect you desire can be achieved by first making sure that the g receives all pointer events:
.g_main {
// ..
pointer-events: all;
}
And then appending an invisible rectangle to it as a place to hover over:
viz.on("mousemove", function () {
cx = d3.mouse(this)[0];
cy = d3.mouse(this)[1];
redrawline(cx, cy);
})
.on("mouseover", function () {
d3.selectAll('.line_over').style("display", "block");
})
.on("mouseout", function () {
d3.selectAll('.line_over').style("display", "none");
})
.append('rect')
.attr('class', 'click-capture')
.style('visibility', 'hidden')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height);
Working example: http://jsfiddle.net/H3W3k/
As for why they work when applied to the svg element (from the docs):
Note that the ‘svg’ element is not a graphics element, and in a Conforming SVG Stand-Alone File a rootmost ‘svg’ element will never be the target of pointer events, though events can bubble to this element. If a pointer event does not result in a positive hit-test on a graphics element, then it should evoke any user-agent-specific window behavior, such as a presenting a context menu or controls to allow zooming and panning of an SVG document fragment.
Related
I am trying to port a d3 chart (which I found online) to v4 but for some reason only the axes are shown and nothing else. The code runs without any errors in the console of Chrome's developer tools and I have hit the wall as I am not an advanced d3 user. Any ideas are highly appreciated.
Here are two jsfiddles, in v3 and v4
https://jsfiddle.net/54mp286c/31/
https://jsfiddle.net/54mp286c/36/
and this is the d3 v4 code
var data = [{
"Cell_Num": 0,
"y": 3,
"x": 2
}, {
"Cell_Num": 1,
"y": 3,
"x": 6
}, {
"Cell_Num": 2,
"y": 7,
"x": 1
}, {
"Cell_Num": 3,
"y": 5,
"x": 5
}]
var margin = {
top: 10,
left: 50,
bottom: 30,
right: 10
},
width = 460 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var scale = {
x: d3.scaleLinear().range([0, width]).nice(),
y: d3.scaleLinear().range([height, 0]).nice()
};
var access = {
x: function(d) {
return d.x;
},
y: function(d) {
return d.y;
}
};
var value = {
x: function(d) {
return scale.x(access.x(d));
},
y: function(d) {
return scale.y(access.y(d));
}
};
var axis = {
x: d3.axisBottom(scale.x),
y: d3.axisLeft(scale.y)
};
var svg = d3.select(".chart").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 + ")");
svg.append("g").attr("class", "x axis");
svg.append("g").attr("class", "y axis");
svg.call(renderPlot, data);
function renderPlot(selection, data) {
updateScales(data);
selection.select(".x.axis").call(axis.x)
.attr("transform", "translate(0," + height + ")");
selection.select(".y.axis").call(axis.y);
selection
.call(renderVoronoi, data)
.call(renderPoints, data);
}
function renderVoronoi(selection, data) {
var voronoi = d3.voronoi()
.x(value.x)
.y(value.y)
.extent([
[0, 0],
[width, height]
]);
var polygons = selection.selectAll(".voronoi")
.data(voronoi(data));
polygons.enter().append("path")
.attr("class", "voronoi")
.on("mouseenter", function(d, i) {
var datum = selection.selectAll(".point").data()[i];
selection.call(renderCrosshair, datum);
})
.on("mouseleave", function(d, i) {
selection.selectAll(".crosshair").remove();
});
polygons
.attr("d", d3.line());
polygons.exit()
.remove();
}
function renderCrosshair(selection, datum) {
var lineData = [
// vertical line
[
[value.x(datum), height],
[value.x(datum), 0]
],
// horizontal line
[
[0, value.y(datum)],
[width, value.y(datum)]
]
];
var crosshairs = selection.selectAll(".crosshair.line").data(lineData);
crosshairs.enter().append("path")
.attr("class", "crosshair line");
crosshairs
.attr("d", d3.svg.line());
crosshairs.exit()
.remove();
var labelData = [{
x: -6,
y: value.y(datum) + 4,
text: Math.round(access.y(datum)),
orient: "left"
},
{
x: value.x(datum),
y: height + 16,
text: Math.round(access.x(datum)),
orient: "bottom"
}
];
var labels = selection.selectAll(".crosshair.label").data(labelData);
labels.enter().append("text")
.attr("class", "crosshair label");
labels
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y;
})
.style("text-anchor", function(d) {
return d.orient === "left" ? "end" : "middle";
})
.text(function(d) {
return d.text;
});
labels.exit().remove();
}
function renderPoints(selection, data) {
var points = selection.selectAll(".point").data(data);
points.enter().append("circle")
.attr("class", "point")
.attr("cx", value.x)
.attr("cy", value.y)
.attr("r", 0)
.style("opacity", 0);
points
.transition().duration(1000)
.attr("cx", value.x)
.attr("cy", value.y)
.attr("r", 2)
.style("opacity", 1);
points.exit()
.transition().duration(1000)
.attr("r", 0)
.style("opacity", 0)
.remove();
}
function updateScales(data) {
var extent = {
x: d3.extent(data, access.x),
y: d3.extent(data, access.y)
};
scale.x.domain([extent.x[0] - 0.5, extent.x[1] + 0.5]);
scale.y.domain([extent.y[0] - 0.5, extent.y[1] + 0.5]);
}
Many thanks!
I am trying to get some data in my map, however I have the following error:
Uncaught TypeError: Cannot read property 'length' of undefined.
This is my code:
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
body { font: 12px Arial;}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 28px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
/* pointer-events: none; This line needs to be removed */
}
</style>
<body>
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
// Set the dimensions of the canvas / graph
var w = window.innerWidth,
h = window.innerHeight,
margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
var formatTime = d3.time.format("%e %B");// Format tooltip date / time
// We're passing in a function in d3.max to tell it what we're maxing (x value)
var x = d3.scale.linear()
.domain([0, d3.max(data, function (d) { return d.x + 10; })])
.range([margin.left, w - margin.right]); // Set margins for x specific
// We're passing in a function in d3.max to tell it what we're maxing (y value)
var y = d3.scale.linear()
.domain([0, d3.max(data, function (d) { return d.y + 10; })])
.range([margin.top, h - margin.bottom]); // Set margins for y specific
// Add a X and Y Axis (Note: orient means the direction that ticks go, not position)
var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
// Define 'div' for tooltips
var div = d3.select("body")
.append("div") // declare the tooltip div
.attr("class", "tooltip") // apply the 'tooltip' class
.style("opacity", 0); // set the opacity to nil
// Adds the svg canvas
var svg = 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 + ")");
// Get the data
var datajson = '[ { x: 100, y: 110 }, { x: 83, y: 43 }, { x: 92, y: 28 }, { x: 49, y: 74 }, { x: 51, y: 10 }, { x: 25, y: 98 }, { x: 77, y: 30 }, { x: 20, y: 83 }, { x: 11, y: 63 }, { x: 4, y: 55 }, { x: 0, y: 0 }, { x: 85, y: 100 }, { x: 60, y: 40 }, { x: 70, y: 80 }, { x: 10, y: 20 }, { x: 40, y: 50 }, { x: 25, y: 31 } ]';
var data = JSON.parse(datajson);
data.forEach(function(d) {
d.x = d.x;
d.y = +d.y;
});
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
// draw the scatterplot
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
// Tooltip stuff after this
.on("mouseover", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
div.transition()
.duration(200)
.style("opacity", .9);
div .html(
'<a href= "http://google.com">' + // The first <a> tag
d.x +
"</a>" + // closing </a> tag
"<br/>" + d.y)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
});
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
</script>
</body>
It goes wrong at line 59:
var y = d3.scale.linear()
.domain([0, d3.max(data, function (d) { return d.y + 10; })])
I am trying to plot line chart with points.
Firstly your JSON string should be like:
var datajson = '[ { "x": 100, "y": 110 },
{ "x": 83, "y": 43 }, { "x": 92, "y": 28 },
{ "x": 49, "y": 74 },
{ "x": 51, "y": 10 }, { "x": 25, "y": 98 },
{ "x": 77, "y": 30 }, { "x": 20, "y": 83 },
{ "x": 11, "y": 63 }, { "x": 4, "y": 55 },
{ "x": 0, "y": 0 }, { "x": 85, "y": 100 },
{ "x": 60, "y": 40 }, { "x": 70, "y": 80 },
{ "x": 10, "y": 0 }, { "x": 40, "y": 50 },
{ "x": 25, "y": 31 } ]';
Note the double codes(") on the key.
Next
You are setting the domain like:
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) {
return d.x + 10;
})])
.range([margin.left, w - margin.right]); //
But data is defined much below this line.
So please move the below lines above:
var data = JSON.parse(datajson);
data.forEach(function(d) {
d.x = d.x;
d.y = +d.y;
});
working code here
I am trying to get responsive d3js charts. I have set the width and height as 100% for the chart have a resize function which should reduce the size . In what I have done so far it just manages to reduce the labels on the x-axis but the line chart remains of the same size.Is the way I am trying to make the responsive the correct way or is their a better way with which any d3js chart(bar/pie/line) could be made responsive.
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var width = parseInt(d3.select("#chart").style("width")) - margin.left - margin.right,
height = parseInt(d3.select("#chart").style("height")) - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5).tickFormat(function (d) {
return d.replace('SEASONAL_', '');
});;
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function (d) {
return x(d.name);
})
.y(function (d) {
return y(d.count);
});
var svg = 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 + ")");
// Get the data
var all = [{
"name": "Seasonal Pop",
"code": "SEASONAL_POP",
"children": [{
"name": "SEASONAL_LYQ1",
"code": "SEASONAL_LYQ1",
"count": 1200
}, {
"name": "SEASONAL_LYQ2",
"code": "SEASONAL_LYQ2",
"count": 2000
}, {
"name": "SEASONAL_LYQ3",
"code": "SEASONAL_LYQ3",
"count": 1060
}, {
"name": "SEASONAL_LYQ4",
"code": "SEASONAL_LYQ4",
"count": 2300
}, {
"name": "SEASONAL_CYQ1",
"code": "SEASONAL_CYQ1",
"count": 1300
}, {
"name": "SEASONAL_CYQ2",
"code": "SEASONAL_CYQ2",
"count": 3400
}, {
"name": "SEASONAL_CYQ3",
"code": "SEASONAL_CYQ3",
"count": 4500
}, {
"name": "SEASONAL_CYQ4",
"code": "SEASONAL_CYQ4",
"count": 5500
}]
}];
var data = all[0].children;
data.forEach(function (d) {
// d.name = +d.date ;
d.count = +d.count;
});
// Scale the range of the data
x.domain(data.map(function (d) {
return d.name;
}));
y.domain([0, d3.max(data, function (d) {
return d.count;
})]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
// Define responsive behavior
function resize() {
var width = parseInt(d3.select("#chart").style("width")) - margin.left - margin.right,
height = parseInt(d3.select("#chart").style("height")) - margin.top - margin.bottom;
// Update the range of the scale with new width/height
x.range([0, width]);
y.range([height, 0]);
// Update the axis and text with the new scale
svg.select('.x.axis')
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.select('.y.axis')
.call(yAxis);
// Force D3 to recalculate and update the line
svg.selectAll('.line')
.attr("d", function(d) { return line(d.count); });
// Update the tick marks
xAxis.ticks(Math.max(width/75, 2));
yAxis.ticks(Math.max(height/50, 2));
};
// Call the resize function whenever a resize event occurs
d3.select(window).on('resize', resize);
// Call the resize function
resize();
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
#chart {
width: 100%;
height: 100%;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body><svg id="chart"></svg></body>
Well your code kinda works. Save that you're dealing with two SVGs. The on the page with id="chart" and this one thats appended.
var svg = d3.select("body")
.append("svg")
But its not really a D3 issue its more to do with responsive SVGs. Responsive charts have problems scaling. The X & Y axis can become misrepresented.
One approach is to scale the entire Chart/SVG. Forget about listening to window resize events. Just set a viewBox property on your main svg. And set a static width hight thats too the correct ratio of your chat.
var svg = d3.select("#chart")
.attr("viewBox", "0 0 " + viewWidth + " " + viewHeight)
example
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var width = 500 - margin.left - margin.right,
height = 240 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5).tickFormat(function (d) {
return d.replace('SEASONAL_', '');
});;
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function (d) {
return x(d.name);
})
.y(function (d) {
return y(d.count);
});
var viewWidth = width - margin.left - margin.right;
var viewHeight = height + margin.top + margin.bottom;
var svg = d3.select("#chart")
.attr("viewBox", "0 0 " + viewWidth + " " + viewHeight)
// Get the data
var all = [{
"name": "Seasonal Pop",
"code": "SEASONAL_POP",
"children": [{
"name": "SEASONAL_LYQ1",
"code": "SEASONAL_LYQ1",
"count": 1200
}, {
"name": "SEASONAL_LYQ2",
"code": "SEASONAL_LYQ2",
"count": 2000
}, {
"name": "SEASONAL_LYQ3",
"code": "SEASONAL_LYQ3",
"count": 1060
}, {
"name": "SEASONAL_LYQ4",
"code": "SEASONAL_LYQ4",
"count": 2300
}, {
"name": "SEASONAL_CYQ1",
"code": "SEASONAL_CYQ1",
"count": 1300
}, {
"name": "SEASONAL_CYQ2",
"code": "SEASONAL_CYQ2",
"count": 3400
}, {
"name": "SEASONAL_CYQ3",
"code": "SEASONAL_CYQ3",
"count": 4500
}, {
"name": "SEASONAL_CYQ4",
"code": "SEASONAL_CYQ4",
"count": 5500
}]
}];
var data = all[0].children;
data.forEach(function (d) {
// d.name = +d.date ;
d.count = +d.count;
});
// Scale the range of the data
x.domain(data.map(function (d) {
return d.name;
}));
y.domain([0, d3.max(data, function (d) {
return d.count;
})]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
#chart {
width: 100%;
height: 100%;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body><svg id="chart"></svg></body>
I am kind a new to d3.js and want to draw a horizontal grid line based on y coordinate value fiddle , i've tried with if condition at y1 and y2 locations but the lines are overlapping at the top of graph.
Any help is much appreciated.
Your if statement makes little sense to me:
if (y(d) === thresholdValues.minValue) {
return y(d);
}
This means that only when the value in the screen is exactly thresholdValues.minValue (which is 40 in your code) the line will be painted.
Solution: drop the if statement. Actually, I kept the if just to avoid the first gridline, over the x axis:
if (d != 0) {
return y(d);
}
Here is your code with that change:
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var thresholdValues = {
minValue: 40,
maxValue: 85
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close);
});
var svg = 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 + ")");
// Get the data
var data = [{
date: "1-May-12",
close: "58.13"
}, {
date: "30-Apr-12",
close: "53.98"
}, {
date: "27-Apr-12",
close: "67.00"
}, {
date: "26-Apr-12",
close: "89.70"
}, {
date: "25-Apr-12",
close: "99.00"
}];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, 100]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
svg.selectAll("line.horizontalGrid").data(y.ticks(4)).enter()
.append("line")
.attr({
"class": "horizontalGrid",
"x1": margin.right,
"x2": width - margin.right,
"y1": function(d) {
if (d != 0) {
return y(d);
}
},
"y2": function(d) {
if (d != 0) {
return y(d);
}
},
"fill": "none",
"shape-rendering": "crispEdges",
"stroke": "grey",
"stroke-width": "2px",
"opacity": 0.4,
"stroke-dasharray": 8
});
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
EDIT: If you want to draw only two lines, at the thresholds, you have to pass their values to data, not the scale ticks:
.data(Object.values(thresholdValues))
Here is the demo:
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var thresholdValues = {
minValue: 40,
maxValue: 85
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close);
});
var svg = 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 + ")");
// Get the data
var data = [{
date: "1-May-12",
close: "58.13"
}, {
date: "30-Apr-12",
close: "53.98"
}, {
date: "27-Apr-12",
close: "67.00"
}, {
date: "26-Apr-12",
close: "89.70"
}, {
date: "25-Apr-12",
close: "99.00"
}];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, 100]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
svg.selectAll("line.horizontalGrid").data(Object.values(thresholdValues)).enter()
.append("line")
.attr({
"class": "horizontalGrid",
"x1": margin.right,
"x2": width - margin.right,
"y1": function(d) {
if (d != 0) {
return y(d);
}
},
"y2": function(d) {
if (d != 0) {
return y(d);
}
},
"fill": "none",
"shape-rendering": "crispEdges",
"stroke": "grey",
"stroke-width": "2px",
"opacity": 0.4,
"stroke-dasharray": 8
});
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.js"></script>
I want to draw an xy multiseries linechart with d3.js. Thats ok.
But afterwards I want to scale the x-axes ordinal.
so thats the code of my xy linechart:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
div.tooltip {
position: absolute;
text-align: center;
padding: 5px;
font: 14px sans-serif;
background: black;
color: white;
border: 0px;
border-radius: 8px;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1px;
}
</style>
<body>
<script src="d3.js"></script>
<script src="jquery-2.1.4.js" charset="utf-8"></script>
<script>
var margin = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
width = 1180 - margin.left - margin.right,
height = 580 - margin.top - margin.bottom;
var x = d3.scale.linear().rangeRound([0, width]);
var y = d3.scale.linear().rangeRound([height, 0]);
var linearScale = d3.scale.linear();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = 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 + ")");
/* var line = d3.svg.line()
.x(function(d) { console.log('x'+x(d.arbeitsgang));return x(d.arbeitsgang); })
.y(function(d) { console.log('y'+y(d.koordinaten));return y(d.koordinaten); });
*/
var line = d3.svg.line()
.x(function (d) {
return x(d.x);
})
.y(function (d) {
return y(d.y);
});
// Define 'div' for tooltips
var div = d3.select("body")
.append("div") // declare the tooltip div
.attr("class", "tooltip") // apply the 'tooltip' class
.style("opacity", 0); // set the opacity to nil
//d3.json("Arbeitsgang.json", function(error, data) {
var data = [
{
"key": "Paket 1",
"values": [
{
"x": 0,
"y": 40,
"arbeitsgang": "A1"
},
{
"x": 6,
"y": 30,
"arbeitsgang": "A2"
},
{
"x": 17,
"y": 20,
"arbeitsgang": "A3"
}
]
},
{
"key": "Paket 3",
"values": [
{
"x": 0,
"y": 85,
"arbeitsgang": "A1"
},
{
"x": 8,
"y": 50,
"arbeitsgang": "A2"
},
{
"x": 17,
"y": 89,
"arbeitsgang": "A3"
}
]
},
{
"key": "Paket 2",
"values": [
{
"x": 0,
"y": 45,
"arbeitsgang": "A1"
},
{
"x": 6,
"y": 145,
"arbeitsgang": "A1"
},
{
"x": 17,
"y": 53,
"arbeitsgang": "A1"
}
]
}
];
linearScale.domain(d3.keys(data[0]).filter(function (key) {
return key;
}));
x.domain([
d3.min(data, function (c) {
return d3.min(c.values, function (v) {
return v.x;
});
}),
d3.max(data, function (c) {
return d3.max(c.values, function (v) {
return v.x;
});
})
]);
y.domain([
d3.min(data, function (c) {
return d3.min(c.values, function (v) {
return v.y;
});
}),
d3.max(data, function (c) {
return d3.max(c.values, function (v) {
return v.y;
});
})
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var graphen = svg.selectAll(".graphen")
.data(data)
.enter().append("g")
.attr("class", "graphen");
var graph = graphen.append("path")
.attr("class", "line")
.attr("d", function (d) {
return line(d.values);
});
graph.on("mouseover", function (d) {
d3.select(this).style("stroke-width", 7);
div.transition()
.duration(200)
.style("opacity", .9);
div.html(d.key)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
div.style("visibility", "visible");
var selectthegraphs = $('.line').not(this); //select all the rest of the lines, except the one you are hovering on and drop their opacity
d3.selectAll(selectthegraphs)
.style("opacity", 0.2);
var selectcircles = $('.circle');
d3.selectAll(selectcircles)
.style("opacity", 0.2);
})
.on("mouseout", function () {
d3.select(this).style("stroke-width", 1);
div.transition()
.duration(500)
.style("opacity", 0.01);
div.style("visibility", "hidden");
var selectthegraphs = $('.line'); //select all the rest of the lines, except the one you are hovering on and drop their opacity
d3.selectAll(selectthegraphs)
.style("opacity",1);
var selectcircles = $('.circle');
d3.selectAll(selectcircles)
.style("opacity", 1);
});
graphen.each(function (p, j) {
d3.select(this).selectAll("circle")
.data(p.values)
.enter().append("circle")
.style("stroke", "black")
.style("fill", "white")
.attr("class","circle")
.attr("r", 5)
.attr("cx", function (d) {
return x(d.x);
})
.attr("cy", function (d) {
return y(d.y);
})
.on("mouseover", function (d) {
d3.select(this).transition().duration(500)
.attr("r", 10);
div.transition()
.duration(500)
.style("opacity", 0.9);
div.style("visibility", "visible");
div.html("X: " + d.x + "<br/>" + "Y: " + d.y + "<br/>" + "Arbeitsgang: " + d.arbeitsgang)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function (d) {
d3.select(this).transition().duration(500)
.attr("r", 5);
div.transition()
.duration(500)
.style("opacity", 0);
div.style("visibility", "hidden");
})
});
ok. but now I want the same graph with an ordinal scale.
The ticks shall be "data.values.arbeitsgang"
"arbeitsgang": "A1" for example.
please help me
Ordinal scales are not so tough.
var x = d3.scale.ordinal()
.domain(["A1","A2","A3"])
.rangeRoundPoints([0, width]);
The scale should now divide the range going from 0 to your width into 3 equally large parts. I choose for rangeRoundPoints because the values of the ticks are rounded to integers then and I like integers.
I believe you can customize the text of the x axis (of course using your ordinal scale to scale the axis), showing "Arbeitsgang:A1" for example, but I wouldn't know how to do that right on the top of my head.
For more information about ordinal scales, check out this link. Unless I totally misunderstood the question, I think this is the only thing you need.
I realize that I have hardcoded the values of the domain, but an array containing the values will do as well.