Related
I would like to add a tooltip to the line chart, where each data point displays a text box upon hover, as follows:
-----------------|
x-coordinate: ## |
y-coordinate: ## |
-----------------|
The working snippet for the working graph is posted below. But I will comment out the tooltip block to plot the chart.
Thanks.
var margin = {top: 50, right: 50, bottom: 50, left: 50}
, width = window.innerWidth - margin.left - margin.right
, height = window.innerHeight - margin.top - margin.bottom;
//labels
var labels = ['Mon','Tue','Thur','Frid'];
var yvals = [12,11,0,18];
// X scale
var xScale = d3.scalePoint()
.domain(labels) // input
.range([0, width-1]); // output
// Y scale
var yScale = d3.scaleLinear()
.domain([0, 20])
.range([height,0]);
var line = d3.line()
.x(function(d, i) { return xScale(labels[i]); })
.y(function(d) { return yScale(d.y); })
.curve(d3.curveMonotoneX)
var dataset = d3.range(yvals.length).map(function(d,i) { return {"y": yvals[i]} })
//Tooltip
//var tip = d3.select('body')
//.append('div')
//.attr('class', 'tip')
//.html('number:'+ function(d,i) return {data[data.i]})
// .style('border', '1px solid steelblue')
// .style('padding', '5px')
//.style('position', 'absolute')
// .style('display', 'none')
//.on('mouseover', function(d, i) {
// tip.transition().duration(0);
// })
// .on('mouseout', function(d, i) {
// tip.style('display', 'none');
// });
// SVGs
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 + ")");
svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "white");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// x axis call
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
//.call(d3.axisBottom(xScale));
.call(d3.axisBottom(xScale));
// y axis call
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale));
svg.append("path")
.datum(dataset)
.attr("class", "line")
.attr("d", line);
// 12. Appends a circle for each datapoint
svg.selectAll(".dot")
.data(dataset)
.enter().append("circle") // Uses the enter().append() method
.attr("class", "dot") // Assign a class for styling
.attr("cx", function(d, i) { return xScale(labels[i]) })
.attr("cy", function(d,i) { return yScale(yvals[i]) })
.attr("r", 3);
//.on('mouseover', function(d, i) {
// tip.transition().duration(0);
// })
svg.append("text")
.attr("class", "title")
.attr("x", width/2)
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.text("Testing");
.line {
fill: none;
stroke: orange;
stroke-width: 1;
}
.dot {
fill: brown;
stroke: #fff;
}
<!DOCTYPE html>
<meta charset="utf-8">
<style type="text/css">
</style>
<body>
</body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
</script>
I have just made a few changes to the mousemove event.
var margin = {
top: 50,
right: 50,
bottom: 50,
left: 50
},
width = window.innerWidth - margin.left - margin.right,
height = window.innerHeight - margin.top - margin.bottom;
//labels
var labels = ['Mon', 'Tue', 'Thur', 'Frid'];
var yvals = [12, 11, 0, 18];
// X scale
var xScale = d3.scalePoint()
.domain(labels) // input
.range([0, width - 1]); // output
// Y scale
var yScale = d3.scaleLinear()
.domain([0, 20])
.range([height, 0]);
var line = d3.line()
.x(function(d, i) {
return xScale(labels[i]);
})
.y(function(d) {
return yScale(d.y);
})
.curve(d3.curveMonotoneX)
var dataset = d3.range(yvals.length).map(function(d, i) {
return {
"y": yvals[i]
}
})
var tip = d3.select('body').append("div")
.attr("class", "tip");
// SVGs
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 + ")");
svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "white");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// x axis call
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
//.call(d3.axisBottom(xScale));
.call(d3.axisBottom(xScale));
// y axis call
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale));
svg.append("path")
.datum(dataset)
.attr("class", "line")
.attr("d", line);
// 12. Appends a circle for each datapoint
svg.selectAll(".dot")
.data(dataset)
.enter().append("circle") // Uses the enter().append() method
.attr("class", "dot") // Assign a class for styling
.attr("cx", function(d, i) {
return xScale(labels[i])
})
.attr("cy", function(d, i) {
return yScale(yvals[i])
})
.attr("r", 3)
.on("mouseover", function() {
tip.style("display", null);
})
.on("mouseout", function() {
tip.style("display", "none");
})
.on("mousemove", function(d) {
return tip
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + 10 + "px")
.style("visibility", "visible")
.html(function() {
return '<div style="border:1px solid #ccc;">' +
'<p style="font-weight:bold;">' + d.y + '</p>' +
'</div>';
})
})
svg.append("text")
.attr("class", "title")
.attr("x", width / 2)
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.text("Testing");
.line {
fill: none;
stroke: orange;
stroke-width: 1;
}
.dot {
fill: brown;
stroke: #fff;
}
.tip {
position: absolute;
border: 1px solid steelblue;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.0.0/d3.min.js"></script>
Here is the working jsFiddle
Hope it helps :)
Right now i have a brush function and two lines. I could add tiptool without brush function but since i have brush now, it wont focus anymore. And also i have two lines, so its hard to choose a appropriate tiptool. I wanted to add the tiptool only on the upper margin. I am new in javascript. Anyone could help me with it? Thank you so much
var margin = {
top: 10,
right: 10,
bottom: 100,
left: 40
},
margin2 = {
top: 430,
right: 10,
bottom: 20,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
height2 = 500 - margin2.top - margin2.bottom;
var color = d3.scale.category10();
var parseDate = d3.time.format("%m/%e/%Y %H:%M").parse;
var x = d3.time.scale().range([0, width]),
x2 = d3.time.scale().range([0, width]),
y = d3.scale.linear().range([height, 0]),
y2 = d3.scale.linear().range([height2, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom"),
xAxis2 = d3.svg.axis().scale(x2).orient("bottom"),
yAxis = d3.svg.axis().scale(y).orient("left");
var brush = d3.svg.brush()
.x(x2)
.on("brush", brush);
var line = d3.svg.line()
.defined(function(d) {
return !isNaN(d.power);
})
.interpolate("cubic")
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.power);
});
var line2 = d3.svg.line()
.defined(function(d) {
return !isNaN(d.power);
})
.interpolate("cubic")
.x(function(d) {
return x2(d.date);
})
.y(function(d) {
return y2(d.power);
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
d3.csv("pvdata2.csv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) {
return key !== "pvdate";
}));
data.forEach(function(d) {
d.date = parseDate(d.pvdate);
});
var sources = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {
date: d.date,
power: +d[name]
};
})
};
});
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([d3.min(sources, function(c) {
return d3.min(c.values, function(v) {
return v.power;
});
}),
d3.max(sources, function(c) {
return d3.max(c.values, function(v) {
return v.power;
});
})
]);
x2.domain(x.domain());
y2.domain(y.domain());
var focuslineGroups = focus.selectAll("g")
.data(sources)
.enter().append("g");
var focuslines = focuslineGroups.append("path")
.attr("class", "line")
.attr("d", function(d) {
return line(d.values);
})
.style("stroke", function(d) {
return color(d.name);
})
.attr("clip-path", "url(#clip)");
focus.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "y axis")
.call(yAxis);
var contextlineGroups = context.selectAll("g")
.data(sources)
.enter().append("g");
var contextLines = contextlineGroups.append("path")
.attr("class", "line")
.attr("d", function(d) {
return line2(d.values);
})
.style("stroke", function(d) {
return color(d.name);
})
.attr("clip-path", "url(#clip)");
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height2 + 7);
svg.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 45)
.attr("dy", "0.71em")
.style("text-anchor", "end")
.text("Power (kW)");
});
function brush() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.selectAll("path.line").attr("d", function(d) {
return line(d.values)
});
focus.select(".x.axis").call(xAxis);
focus.select(".y.axis").call(yAxis);
}
// Active point element
var activePoint = svg.append('circle')
.attr({
cx: 0,
cy: 0,
r: 5,
'pointer-events': 'none'
})
.style({
stroke: 'none',
fill: 'red',
'fill-opacity': 0
});
svg {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.y.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.brush .extent {
stroke: #fff;
fill-opacity: .125;
shape-rendering: crispEdges;
}
.line {
fill: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I have created a D3 visualization which contains both a scatterplot and a line chart. They share an x-axis, but each have their own y-axis. My problem involves how to properly implement a brush and update both y-axes.
As you can see here the y-axes are correct initially and also correct again once the brush is turned off. However during 'brushing' both y-axes are set to the 'left' one. I see why this is happening when I setup my brush here:
brush = d3.svg.brush()
.x(brushFilterXScale)
.y(brushFilterTransactionsYScale)
.on('brush', brushed);
I also have a brushFilterBalanceYScale which is the scale for the axis on the right. My question is how do I pass BOTH of these scales to brush so that I can update each y-axis properly?
I don't know of a straight-forward way to do this. You can, however, reverse map it in your brush event:
function brushed() {
var extent = brush.extent(), //<-- the extent
yDomain = [extent[0][1], extent[1][1]]; //<-- the y domain of the extent
y2.domain(
[
y2Brush.invert(yBrush(yDomain[0])), //<-- take the yDomain start, get it's pixel position, then invert that back into the domain of the y2Brush
y2Brush.invert(yBrush(yDomain[1]))
]
);
Here's a working example:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
}
.line {
fill: none;
stroke: steelblue;
clip-path: url(#clip);
}
circle {
clip-path: url(#clip);
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.brush .extent {
stroke: #fff;
fill-opacity: .125;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {
top: 10,
right: 40,
bottom: 100,
left: 40
},
margin2 = {
top: 430,
right: 40,
bottom: 20,
left: 40
},
width = 500 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
height2 = 500 - margin2.top - margin2.bottom;
var x = d3.scale.linear().range([0, width])
y = d3.scale.linear().range([height, 0]),
y2 = d3.scale.linear().range([height, 0]),
xBrush = d3.scale.linear().range([0,width]),
yBrush = d3.scale.linear().range([height2, 0]),
y2Brush = d3.scale.linear().range([height2, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom"),
yAxis = d3.svg.axis().scale(y).orient("left"),
yAxis2 = d3.svg.axis().scale(y2).orient("right"),
yAxisBrush = d3.svg.axis().scale(yBrush).orient("bottom");
xAxisBrush = d3.svg.axis().scale(xBrush).orient("bottom");
var brush = d3.svg.brush()
.x(xBrush)
.y(yBrush)
.on("brush", brushed);
var line = d3.svg.line()
.interpolate("monotone")
.x(function(d) {
return x(d.x);
})
.y(function(d) {
return y(d.y);
});
var lineBrush = d3.svg.line()
.interpolate("monotone")
.x(function(d) {
return x(d.x);
})
.y(function(d) {
return yBrush(d.y);
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
var data1 = [],
data2 = [];
for (var i = 0; i < 100; i++) {
data1.push({
x: i,
y: Math.random() * 10
});
if (i % 3 === 0){
data2.push({
x: i,
y: Math.random() * 100
});
}
}
x.domain([0,100]);
y.domain([0, d3.max(data1.map(function(d) {
return d.y;
}))]);
y2.domain([0, d3.max(data2.map(function(d) {
return d.y;
}))]);
xBrush.domain(x.domain());
yBrush.domain(y.domain());
y2Brush.domain(y2.domain());
focus.append("path")
.datum(data1)
.attr("class", "line")
.attr("d", line);
var scatter = focus.append("g")
.selectAll("circle")
.data(data2);
scatter
.enter()
.append("circle")
.attr("cx", function(d){
return x(d.x);
})
.attr("cy", function(d){
return y2(d.y);
})
.attr("r", function(d){
d.r = Math.random() * 20;
return d.r;
})
.style("fill", "orange")
.style("opacity", "0.5");
focus.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "y axis")
.call(yAxis);
focus.append("g")
.attr("transform", "translate(" + width + " ,0)")
.attr("class", "y2 axis")
.call(yAxis2);
context.append("path")
.datum(data1)
.attr("class", "line")
.attr("d", lineBrush);
context.append("g")
.selectAll("circle")
.data(data2)
.enter()
.append("circle")
.attr("cx", function(d){
return x(d.x);
})
.attr("cy", function(d){
return y2Brush(d.y);
})
.attr("r", function(d){
return d.r * 0.25;
})
.style("fill", "orange")
.style("opacity", "0.5");
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxisBrush);
context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height2 + 7);
function brushed() {
var extent = brush.extent(),
yDomain = [extent[0][1], extent[1][1]];
y2.domain([y2Brush.invert(yBrush(yDomain[0])), y2Brush.invert(yBrush(yDomain[1]))]);
x.domain(brush.empty() ? xBrush.domain() : [extent[0][0], extent[1][0]]);
y.domain(brush.empty() ? yBrush.domain() : yDomain);
scatter
.attr("cx", function(d){
return x(d.x);
})
.attr("cy", function(d){
return y2(d.y);
})
focus.select(".line").attr("d", line);
focus.select(".x.axis").call(xAxis);
focus.select(".y.axis").call(yAxis);
focus.select(".y2.axis").call(yAxis2);
}
</script>
UPDATED
Problem
a) Only one of my bar charts is showing after I switched a variable var csvData in my scripts.js to the real data from the dummy data. The previous data referenced states and demographics, which has now been switched to food and their prices.
scripts.js (UPDATED, chart still not showing up)
$(function() {
$("#placeholder").remove();
var margin = {top: 60, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// X is the horizontal axis
var x0 = d3.scale.ordinal() // ordinal for non quantitative scales, like names, categories
.rangeRoundBands([0, width], .1); // Width of each individual bar?
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
// Bar chart colors
var color = d3.scale.ordinal()
.range(["#001F4C", "#003D99", "#005CE6", "#0066FF", "#3385FF", "#80B2FF", "#CCE0FF", "#E6F0FF", "#E6EBFA"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left") // Where the Y axis goes, you'll want it on the left
.ticks(8)
.tickValues([0, 1, 2, 3, 4, 5, 6]);
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 + ")");
// Bar chart data
var csvData = [
{"Store":"Co-op","Broccoli":2.69,"Cauliflower":3.69,"Celery":1.89,"Strawberries":4.49,"Oranges":1.69,"Tomatoes":3.49,"Lemons":0.99, "Lettuce":0.01, "Cucumber":2},
{"Store":"Safeway","Broccoli":2.97,"Cauliflower":3.98,"Celery":1.77,"Strawberries":5.96,"Oranges":0.97,"Tomatoes":2.97,"Lemons":0.77, "Lettuce":4.97, "Cucumber":1.97},
{"Store":"Sobeys","Broccoli":3.49,"Cauliflower":3.99,"Celery":1.29,"Strawberries":3.99,"Oranges":1.99,"Tomatoes":4.99,"Lemons":1.29, "Lettuce":3.49, "Cucumber":1.99},
{"Store":"Superstore","Broccoli":2.69,"Cauliflower":2.49,"Celery":1.09,"Strawberries":2.99,"Oranges":0.99,"Tomatoes":3.99,"Lemons":0.99, "Lettuce":4.99, "Cucumber":2.49},
];
var data = csvData;
var foodNames = d3.keys(data[0]).filter(function(key) { return key !== "Store"; });
data.forEach(function(d) {
d.food = foodNames.map(function(name) { return {name: name, value: +d[name]}; });
});
x0.domain(data.map(function(d) { return d.Store; }));
x1.domain(foodNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.food, function(d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)") // Rotates the label on the Y axis
.attr("y", 8) // Label spacing from Y axis
.attr("dy", ".71em") // Label spacing from Y axis
.style("text-anchor", "end") // Anchor the label to the end of the Y axis
.text("Price (in dollars)"); // Changes the text on the Y or vertical axis
var store = svg.selectAll(".store") // Selects all of the data in column labelled store
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x0(d.store) + ",0)"; });
store.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("class", "stick")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 22.5 + ")"; }); // Determines spacing between items in legend
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="assets/js/scripts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
</body>
</html>
style.css
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
/*.stick {
fill: steelblue;
}
.stick:hover {
fill: brown;
}*/
.x.axis path {
display: none;
}
$(function() {
$("#placeholder").remove();
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// X is the horizontal axis
var x0 = d3.scale.ordinal() // ordinal for non quantitative scales, like names, categories
.rangeRoundBands([0, width], .1); // Width of each individual bar?
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0])
// These are the colors
var color = d3.scale.ordinal()
// .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
.range(["#001F4C", "#003D99", "#005CE6", "#0066FF", "#3385FF", "#80B2FF", "#CCE0FF", "#E6F0FF"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left") // Where the Y axis goes, you'll want it on the left
// .tickFormat(d3.format(".1s"));
.ticks(6);
//.tickValues([0, 1, 2, 3, 4, 5]);
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 + ")");
// Bar chart data
var csvData = [
{"State":"Co-op","Broccoli":2027307,"Cauliflower":3277946,"Celery":1420518,"Strawberries":2454721,"Oranges":7017731,"Tomatoes":5656528,"Lemons":2472223, "Lettuce":2472223, "Cucumber":2472223},
{"State":"Safeway","Broccoli":2704659,"Cauliflower":4499890,"Celery":2159981,"Strawberries":3853788,"Oranges":10604510,"Tomatoes":8819342,"Lemons":4114496, "Lettuce":2472223, "Cucumber":2472223},
{"State":"Sobeys","Broccoli":1140516,"Cauliflower":1938695,"Celery":925060,"Strawberries":1607297,"Oranges":4782119,"Tomatoes":4746856,"Lemons":3187797, "Lettuce":2472223, "Cucumber":2472223},
{"State":"Superstore","Broccoli":1208495,"Cauliflower":2141490,"Celery":1058031,"Strawberries":1999120,"Oranges":5355235,"Tomatoes":5120254,"Lemons":2607672, "Lettuce":2472223, "Cucumber":2472223},
];
// Food Prices
// var csvData = [
// {"Store":"Sobey","Broccoli":2.69,"Cauliflower":3.69,"Celery":$1.89,"Strawberries":$4.49,"Oranges":"1.69,"Tomatoes":$3.49,"Lemons":$0.99,"Lettuce":$0.00,"Cucumber":2.00},
// {"Store":"Superstore","Broccoli":2.97,"Cauliflower":3.98,"Celery":1.77,"Strawberries":5.96,"Oranges":0.97,"Tomatoes":2.97,"Lemons":0.77,"Lettuce":4.97,"Cucumber":1.97},
// {"Store":"Safeway","Broccoli":3.49,"Cauliflower":3.99,"Celery":1.29,"Strawberries":3.99,"Oranges":1.99,"Tomatoes":4.99,"Lemons":1.29,"Lettuce":3.49,"Cucumber":1.99},
// {"Store":"Coop","Broccoli":2.69,"Cauliflower":"2.49","Celery":"1.09","Strawberries":"2.99","Oranges":"0.99","Tomatoes":"3.99","Lemons":"0.99","Lettuce":"4.99","Cucumber":"2.49"}
// ];
// AgeNames = FoodNames
// States = Stores
var data = csvData;
var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
data.forEach(function(d) {
d.ages = ageNames.map(function(name) { return {name: name, value: (+d[name])/2000000}; });
});
x0.domain(data.map(function(d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) {
return d3.max(d.ages, function(c) {
return c.value;
});
})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)") // Rotates the label on the Y axis
.attr("y", 8) // Label spacing from Y axis
.attr("dy", ".71em") // Label spacing from Y axis
.style("text-anchor", "end") // Anchor the label to the end of the Y axis
.text("Price (in dollars)"); // Changes the text on the Y or vertical axis
var state = svg.selectAll(".state") // Selects all of the data in column labelled State
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("class", "stick")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 22.5 + ")"; });
// Number (20) determines spacing between items in legend
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
/*.stick {
fill: steelblue;
}
.stick:hover {
fill: brown;
}*/
.x.axis path {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
To achieve our requirement I've added one thing,i.e.
(+d[name])/2000000 while assigning the value I'm just dividing it to fit to our scale. y domain is set to very big number like near to one Crore.
That's the CSV file: http://goo.gl/ZVVjD
I've this problem only for bar chart. The line chart works fine. I don't know how to modify this one.
Please,help me to understand where I'm wrong.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
//var formatPercent = d3.format("04d");
//var formatPercent = d3.format(".0%");
var parseDate = d3.time.format("%d-%b-%y-%H:%M:%S").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");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
//.tickFormat(formatPercent);
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 + ")");
d3.csv("data.tsv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
//d.energy = parseInt(d.energy);
d.energy = +d.energy;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.energy; })]);
//y.domain(d3.extent(data, function(d) { return d.energy; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Energy");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.date); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.energy); })
.attr("height", function(d) { return height - y(d.energy); });
});
</script>
Thank you very much!
I don't believe x.rangeBand() works for time scales. Try replacing it with with a fixed pixel value of 2 or 3.