In the fiddle below, you can notice that the first bar has the label no even though its value is zero.
How do I remove the labels with zero values in my stacked bar chart?
jsFiddle
CODE:
var data = [
{
"episode": "Ep. 01",
"yes": "100",
"no": "0"
},
{
"episode": "Ep. 02",
"yes": "70",
"no": "30"
},
{
"episode": "Ep. 03",
"yes": "50",
"no": "50"
},
{
"episode": "Ep. 04",
"yes": "90",
"no": "10"
},
{
"episode": "Ep. 05",
"yes": "30",
"no": "70"
},
{
"episode": "Ep. 06",
"yes": "60",
"no": "40"
},
{
"episode": "Ep. 07",
"yes": "70",
"no": "30"
},
{
"episode": "Ep. 08",
"yes": "50",
"no": "50"
},
{
"episode": "Ep. 09",
"yes": "90",
"no": "10"
},
{
"episode": "Ep. 10",
"yes": "30",
"no": "70"
}
];
var margin = {top: 20, right: 100, bottom: 30, left: 40},
width = 600 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(data.map( function(d) { return d.episode; }))
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#B4D92A", "#FF3332"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(10,10);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".0%"));
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom + 100)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.csv("data.csv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "episode"; }));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.ages.forEach(function(d) { d.y0 /= y0; d.y1 /= y0; });
});
//data.sort(function(a, b) { return b.ages[0].y1 - a.ages[0].y1; });
// var unique = data.map(function(d) { return d.episode.substring(0,5)+'...'; });
// x.domain(unique);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll(".tick text")
.call(wrap, x.rangeBand());
svg.selectAll(".ellipse")
.data(data)
.enter()
.append("ellipse")
.attr("cx", function(d) { return x(d.episode) + 14; })
.attr("cy", function(d) { return y(0); })
.attr("rx", 18)
.attr("ry", 5)
.style("fill", "#728220");
var episode = svg.selectAll(".episode")
.data(data)
.enter().append("g")
.attr("class", "episode")
.attr("transform", function(d) { return "translate(" + x(d.episode) + ",0)"; });
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
episode.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand() - 15)
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); })
.on("mouseover", function(d) {
var x=Number($(this).attr("height"))/45;
if($(this).css("fill")=="rgb(255, 51, 50)" || $(this).css("fill")=="#ff3332" ){
tooltip.html("YES: " + Number((10-x)*10) + "%<br/>NO: " + Number(x*10) + "%")
}
else
{
tooltip.html("YES: " + Number((x)*10) + "%<br/>NO: " + Number(10-x)*10 + "%")
}
tooltip.transition().duration(200).style("opacity", .9);
tooltip
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
tooltip.transition().duration(500).style("opacity", 0);
});
/*.attr("rx", 5)
.attr("ry", 5);*/
var label = svg.selectAll(".episode")
.selectAll(".legend")
.data(function(d) { return d.ages; })
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d) { return "translate(" + x.rangeBand() / 2 + "," + y((d.y0 + d.y1) / 2) + ")"; });
label.append("text")
.attr("x", -15)
.attr("dy", "-0.35em")
.attr("transform", "rotate(-90)")
.text(function(d) { return d.name; });
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
//});
There are many ways to handle this, consider this when creating your text elements:
.style("display", function(d) { (test if value is zero) ? "none" : "inline"; }
Implemented in your fiddle here: http://jsfiddle.net/V5fJ7/1/
Or, you could filter your selection before actually creating the text, so they don't get created in the first place:
d3Selection.filter(function(d) { return (conditions of data you wish to keep); })
.append("text")
.etc..
You can see this here: http://jsfiddle.net/V5fJ7/2/
Related
I'm trying to implement click function for a bar graph with x-axis scroll.
When I click the scrollbar the graph x-axis is moving right and the scrollbar is disappearing.
Here is my complete code on codepen: https://codepen.io/sampath-PerOxide/pen/QYdqyZ
var data = [
{ label: "Company Average", value: "20" },
{ label: "Banking & Finance", value: "10" },
{ label: "Research & Development", value: "40" },
{ label: "Design & Innovaon", value: "20" },
{ label: "Sales & Marketing", value: "10" },
{ label: "Company Average1", value: "20" },
{ label: "Banking & Finance1", value: "10" },
{ label: "Research & Development1", value: "40" },
{ label: "Design & Innovaon1", value: "20" },
{ label: "Sales & Marketing1", value: "10" },
{ label: "Company Average2", value: "20" },
{ label: "Banking & Finance2", value: "10" },
{ label: "Research & Development2", value: "40" },
{ label: "Design & Innovaon2", value: "20" },
{ label: "Sales & Marketing2", value: "10" },
{ label: "Company Average3", value: "20" },
{ label: "Banking & Finance3", value: "10" },
{ label: "Research & Development3", value: "40" },
{ label: "Design & Innovaon3", value: "20" },
{ label: "Sales & Marketing3", value: "10" },
{ label: "Company Average4", value: "20" },
{ label: "Banking & Finance4", value: "10" },
{ label: "Research & Development4", value: "40" },
{ label: "Design & Innovaon4", value: "20" },
{ label: "Sales & Marketing4", value: "10" },
{ label: "Company Average5", value: "20" },
{ label: "Banking & Finance5", value: "10" },
{ label: "Research & Development5", value: "40" },
{ label: "Design & Innovaon5", value: "20" },
{ label: "Sales & Marketing5", value: "10" }
];
var margin = { top: 20, right: 10, bottom: 20, left: 40 };
var marginOverview = { top: 30, right: 10, bottom: 20, left: 40 };
var selectorHeight = 40;
var width = 1100 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom - selectorHeight;
var heightOverview = 80 - marginOverview.top - marginOverview.bottom;
var MIN_BAR_WIDTH = 20;
var MIN_BAR_PADDING = 5;
var svg = d3
.select("#atthbd")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom + selectorHeight);
var diagram = svg
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var maxLength = d3.max(
data.map(function(d) {
return d.label.length;
})
);
var barWidth = maxLength * 7;
var numBars = Math.round(width / barWidth);
var isScrollDisplayed = barWidth * data.length > width;
var xscale = d3.scale
.ordinal()
.domain(
data.slice(0, numBars).map(function(d) {
return d.label;
})
)
.rangeBands([0, width], 0.7);
var yscale = d3.scale
.linear()
.domain([0, 40])
.range([height, 0]);
var xAxis = d3.svg
.axis()
.scale(xscale)
.orient("bottom");
var yAxis = d3.svg
.axis()
.scale(yscale)
.orient("left");
var tip2 = d3
.tip()
.attr("class", "d3-tip")
.offset([-10, 0])
.html(function(d2) {
return "<p class='sec-sub-head'>Avg No.of days:" + d2.value + "</p>";
});
svg.call(tip2);
diagram
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, " + height + ")")
.call(xAxis);
diagram
.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("Average No. of days");
var bartext = diagram
.append("g")
.attr("class", "bar-texts")
.selectAll(".bar-text")
.data(data.slice(0, numBars));
var barTextEnter = bartext
.enter()
.append("text")
.attr("class", "bar-text")
.attr("x", function(d) {
return xscale(d.label)+20;
})
.attr("y", function(d) {
return yscale(d.value) - 5;
})
.text(function(d) {
return d.value;
})
.attr("text-anchor", "middle");
var bars = diagram.append("g").attr("class", "bars");
bars
.selectAll("rect")
.data(data.slice(0, numBars), function(d) {
return d.label;
})
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return xscale(d.label);
})
.attr("y", function(d) {
return yscale(d.value);
})
.attr("width", xscale.rangeBand())
.attr("height", function(d) {
return height - yscale(d.value);
})
.on("mouseover", tip2.show)
.on("mouseout", tip2.hide);
if (isScrollDisplayed) {
var xOverview = d3.scale
.ordinal()
.domain(
data.map(function(d) {
return d.label;
})
)
.rangeBands([0, width], 0.2);
yOverview = d3.scale.linear().range([heightOverview, 0]);
yOverview.domain(yscale.domain());
var overviewGroup = diagram.append('g')
.attr('width', width)
.attr('height', heightOverview);
var subBars = overviewGroup
.append("g")
.attr("class", "sub-bars")
.selectAll(".subBar")
.data(data);
subBars
.enter()
.append("rect")
.classed("subBar", true)
.attr({
height: function(d) {
return heightOverview - yOverview(d.value);
},
width: function(d) {
return xOverview.rangeBand();
},
x: function(d) {
return xOverview(d.label);
},
y: function(d) {
return height + heightOverview + yOverview(d.value);
}
});
var overviewRect = overviewGroup.append('rect')
.attr('y', height + marginOverview.top)
.attr('width', width)
.attr('height', heightOverview)
.style("opacity", "0")
.style("cursor", "pointer").on("click", click);
var selectorWidth = (width / (MIN_BAR_WIDTH) * (xOverview.rangeBand()));
var displayed = d3.scale
.quantize()
.domain([0, width])
.range(d3.range(data.length));
var selector=diagram
.append("rect")
.attr("transform", "translate(0, " + (height + margin.bottom) + ")")
.attr("class", "mover")
.attr("x", 0)
.attr("y", 0)
.attr("height", selectorHeight)
.attr("width", Math.round(parseFloat(numBars * width) / data.length))
.attr("pointer-events", "all")
.attr("cursor", "ew-resize")
.call(d3.behavior.drag().on("drag", display));
}
var zoom = d3.behavior.zoom().scaleExtent([1, 1]);
function click() {
var newX = null;
var selectorX = null;
var customScale = d3.scale.linear().domain([0, width]).range([0, ((MIN_BAR_WIDTH + MIN_BAR_PADDING) * data.length)])
selectorX = (d3.event.x - marginOverview.left) - selectorWidth / 2;
newX = customScale(selectorX);
if (selectorX > width - selectorWidth) {
newX = customScale(width - selectorWidth);
selectorX = width - selectorWidth;
} else if (selectorX - (selectorWidth / 2) < 0) {
newX = 0;
selectorX = 0
}
selector.transition().attr("x", selectorX)
bars.transition().duration(300).attr("transform", "translate(" + (-newX) + ",0)");
diagram.transition().duration(300).select(".x.axis").attr("transform", "translate(" + -(newX - (MIN_BAR_WIDTH + MIN_BAR_PADDING) / 2) + "," + (height) + ")");
diagram.select(".y.axis").call(yAxis);
var transformX = (-(d3.event.x - selectorWidth) * ((MIN_BAR_WIDTH + MIN_BAR_PADDING) * data.length) / width);
zoom.translate([-newX, 0])
}
function display() {
var x = parseInt(d3.select(this).attr("x")),
nx = x + d3.event.dx,
w = parseInt(d3.select(this).attr("width")),
f,
nf,
new_data,
rects;
if (nx < 0 || nx + w > width) return;
d3.select(this).attr("x", nx);
f = displayed(x);
nf = displayed(nx);
if (f === nf) return;
new_data = data.slice(nf, nf + numBars);
xscale.domain(
new_data.map(function(d) {
return d.label;
})
);
diagram.select(".x.axis").call(xAxis);
rects = bars.selectAll("rect").data(new_data, function(d) {
return d.label;
});
rects.attr("x", function(d) {
return xscale(d.label);
});
rects
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return xscale(d.label);
})
.attr("y", function(d) {
return yscale(d.value);
})
.attr("width", xscale.rangeBand())
.attr("height", function(d) {
return height - yscale(d.value);
})
.on("mouseover", tip2.show)
.on("mouseout", tip2.hide);
bartext
.data(new_data)
.attr("x", function(d) {
return xscale(d.label)+20;
})
.attr("y", function(d) {
return yscale(d.value) - 5;
})
.text(function(d) {
return d.value;
});
bartext.exit().remove();
rects.exit().remove();
}
How can I move the bars when I click on the X-axis scrollbar?
The X-axis scrollbar is a subgraph of actual graph.
I'm trying to display values on the top of line graph using d3 js. How can I append values to the path of the line graph?
And How can I display month-year as X-axis ticks like May'18, June'19?
I tried using the below code, but the values are not displaying.
lineSvg.selectAll("path")
.data(data)
.enter().append("text")
.attr("class", "line")
.attr("text-anchor", "middle")
.attr("x", function(d) { return 10; })
.attr("y", function(d) { return yscale(d.value) - 5; })
.text(function(d) { return d.value; });
Here is my complete code:
var data = [{
"date": "2018-1",
"value": 40.13,
"status": 1
}, {
"date": "2018-2",
"value": 45.88,
"status": 1
}, {
"date": "2018-3",
"value": 50.89,
"status": 1
}, {
"date": "2018-4",
"value": 55.87,
"status": 1
}, {
"date": "2018-5",
"value": 88.54,
"status": 1
}, {
"date": "2018-6",
"value": 74.41,
"status": 1
}, {
"date": "2018-7",
"value": 98.56,
"status": 1
}, {
"date": "2018-8",
"value": 81.05,
"status": 1
}, {
"date": "2018-9",
"value": 58.13,
"status": 1
}, {
"date": "2018-10",
"value": 95.86,
"status": 1
}, {
"date": "2018-11",
"value": 78.13,
"status": 1
}, {
"date": "2018-12",
"value": 98.86,
"status": 1
}, {
"date": "2019-1",
"value": 105.86,
"status": 0
}, {
"date": "2019-2",
"value": 110.86,
"status": 0
}];
/* Monday 2012 */
var data1 = data
var dateformat = "%Y-%m"
drawTimeSeriesGraph(data1, dateformat);
/*
Tooltip from: http://bl.ocks.org/d3noob/6eb506b129f585ce5c8a
line graph from here: http://www.d3noob.org/2012/12/starting-with-basic-d3-line-graph.html
*/
function drawTimeSeriesGraph(data, dateformat) {
//Set bounds for red dots
var lbound = 0.045,
ubound = 0.075;
// Set the dimensions of the canvas / graph
var margin = {
top: 50,
right: 150,
bottom: 50,
left: 50
},
width = 900 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format(dateformat).parse,
formatDate = d3.time.format(dateformat),
bisectDate = d3.bisector(function(d) {
return d.date;
}).left;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(10);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(10);
// Define the line
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.value);
}).interpolate("linear");
var full_date = new Date();
var day = full_date.getDay(); //returns 0 - 6
var month = full_date.getMonth() + 1; //returns 0 - 11
var year = full_date.getFullYear(); //returns 4 digit year ex: 2000
var my = year + "-" + month;
//alert(my);
// 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 + ")");
var lineSvg = svg.append("g");
var focus = svg.append("g")
.style("display", "none");
// Get the data
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.value;
})]);
//Use below if instead you want to define the y limits:
//y.domain([0, 0.11]);
// Add the valueline path.
var lineGraph2 = lineSvg.append("path")
.attr("class", "line")
.attr("d", valueline(data.filter(function(d) {
return d.status > 0;
})))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
var lineGraph1 = lineSvg.append("path")
.attr("class", "line")
.attr("d", valueline(data.slice(-3)))
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("fill", "none");
// 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);
// append the x line
focus.append("line")
.attr("class", "x")
.style("stroke", "blue")
.style("stroke-dasharray", "3,3")
.style("opacity", 0.5)
.attr("y1", 0)
.attr("y2", height);
// append the y line
focus.append("line")
.attr("class", "y")
.style("stroke", "blue")
.style("stroke-dasharray", "3,3")
.style("opacity", 0.5)
.attr("x1", width)
.attr("x2", width);
// append the circle at the intersection
focus.append("circle")
.attr("class", "y")
.style("fill", "none")
.style("stroke", "blue")
.attr("r", 4);
// place the value at the intersection
focus.append("text")
.attr("class", "y1")
.style("stroke", "white")
.style("stroke-width", "3.5px")
.style("opacity", 0.8)
.attr("dx", 8)
.attr("dy", "-.3em");
focus.append("text")
.attr("class", "y2")
.attr("dx", 8)
.attr("dy", "-.3em");
// place the date at the intersection
focus.append("text")
.attr("class", "y3")
.style("stroke", "white")
.style("stroke-width", "3.5px")
.style("opacity", 0.8)
.attr("dx", 8)
.attr("dy", "1em");
focus.append("text")
.attr("class", "y4")
.attr("dx", 8)
.attr("dy", "1em");
// append the rectangle to capture mouse
svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all")
.on("mouseover", function() {
focus.style("display", null);
})
.on("mouseout", function() {
focus.style("display", "none");
})
.on("mousemove", mousemove);
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.select("circle.y")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")");
focus.select("text.y1")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(d.value.toFixed(2));
focus.select("text.y2")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(d.value.toFixed(2));
focus.select("text.y3")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(formatDate(d.date));
focus.select("text.y4")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.text(formatDate(d.date));
focus.select(".x")
.attr("transform", "translate(" + x(d.date) + "," + y(d.value) + ")")
.attr("y2", height - y(d.value));
focus.select(".y")
.attr("transform", "translate(" + width * -1 + "," + y(d.value) + ")")
.attr("x2", width + width);
};
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
};
I'm trying to get line graph like this:
For the axis you have to set the tickFormat.
xAxis.tickFormat(d3.time.format("%b'%y"));
or if you want full month name
xAxis.tickFormat(d3.time.format("%B'%y"));
For the text just add them like you do with circles or rects
svg.selectAll(".val").data(data)
.enter()
.append('text')
.attr("x", d => x(d.date))
.attr("y", d => y(d.value))
.attr("dy", "-0.5em")
.attr("text-anchor", "middle")
.text(d => d.value);
I am trying to assign different colors to each bars of the stacked bar charts as currently there is only single color in all the four bars but trying to assign different colors to all the four bars as well the stacked value.
Code
var margin = {
top: 20,
right: 160,
bottom: 35,
left: 30
};
var width = 960 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
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 + ")");
/* Data in strings like it would be if imported from a csv */
var data = [{
year: "A",
redDelicious: "10",
mcintosh: "5",
color:"red",
oranges: "19"
}, {
year: "B",
redDelicious: "12",
mcintosh: "12",
color:"blue",
oranges: "15"
}, {
year: "C",
redDelicious: "05",
mcintosh: "10",
color:"green",
oranges: "18"
}, {
year: "D",
redDelicious: "14",
mcintosh: "8",
color:"yellow",
oranges: "12"
},
];
$("#btn").on("click", function(){
d3.selectAll("svg > g > g").remove();
data[1].mcintosh = (Number(data[1].mcintosh) + 1).toString();
console.log(1,data);
update();
});
update();
function update(){
var orangeData = data.map(function(d) {
return {
year: d.year,
oranges: +d.oranges
}
});
console.log(orangeData)
// Transpose the data into layers
var dataset = d3.layout.stack()(["redDelicious", "mcintosh"].map(function(skillset) {
return data.map(function(d) {
return {
x: d.year,
y: +d[skillset]
};
});
}));
console.log(dataset)
// Set x, y and colors
var x = d3.scale.ordinal()
.domain(dataset[0].map(function(d) {
return d.x;
}))
.rangeRoundBands([10, width - 10], 0.02);
var y = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
})])
.range([height, 0]);
var colors = ["#b33040", "#edd"];
var backcolors = ["cyan", "blue","green","gray"];
// Define and draw axes
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width, 0, 0)
.tickFormat(function(d) {
return d
});
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// .tickFormat(d3.time.format("%Y"));
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Creating the Average Bar for the Semester
svg.selectAll(".bar1").data(orangeData).enter().append("g")
.attr("class", "bar1").append("rect")
.attr("x", function(d) {
return x(d.year) ; // center it
})
.attr("width", x.rangeBand()) // make it slimmer
.attr("y", function(d) {
return y(d.oranges);
})
.attr("height", function(d) {
return height - y(d.oranges);
})
.style("fill", function(d, i) {
return backcolors[i];
});
// Create groups for each series, rects for each segment in Stacked Bar
var groups = svg.selectAll("g.cost")
.data(dataset)
.enter().append("g")
.attr("class", "cost")
.style("fill", function(d, i) {
return colors[i];
});
var rect = groups.selectAll("rect")
.data(function(d) {
return d;
})
.enter()
.append("rect")
.attr("x", function(d) {
return x(d.x) + 20 ;
})
.attr("y", function(d) {
return y(d.y0 + d.y);
})
.attr("height", function(d) {
return y(d.y0) - y(d.y0 + d.y);
})
.attr("width", x.rangeBand() -40 );
}
Here is the fiddle for the same
I have a chart created with the code below. I want to add a second y axis positioned to the right which matches the same y scale. The reason I want the y axis on the right also is because of the limit line I have set at 16.5, the chart just doesn’t look right without the 2nd y axis.
<script>
var w = 800;
var h = 550;
var margin = {
top: 58,
bottom: 100,
left: 80,
right: 40
};
var width = w - margin.left - margin.right;
var height = h - margin.top - margin.bottom;
var threshold = 16.5;
var x = d3.scale.ordinal()
.domain(data.map(function(entry){
return entry.key;
}))
.rangeBands([0, width],.2);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d){
return d.value;
})])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var yGridLines = d3.svg.axis()
.scale(y)
.tickSize(-width, 0, 0)
.tickFormat("")
.orient("left");
var svg = d3.select("body").append("svg")
.attr("id", "chart")
.attr("width", w)
.attr("height", h);
var chart = svg.append("g")
.classed("display", true)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
function plot(params){
this.append("g")
.call(yGridLines)
.classed("gridline", true)
.attr("transform", "translate(0,0)")
this.selectAll(".bar")
.data(params.data)
.enter()
.append("rect")
.classed("bar", true)
.attr("x", function (d,i){
return x(d.key);
})
.attr("y", function(d,i){
return y(d.value);
})
.attr("height", function(d,i){
return height - y(d.value);
})
.attr("width", function(d){
return x.rangeBand();
});
this.selectAll(".bar-label")
.data(params.data)
.enter()
.append("text")
.classed("bar-label", true)
.attr("x", function(d,i){
return x(d.key) + (x.rangeBand()/2)
})
.attr("dx", 0)
.attr("y", function(d,i){
return y(d.value);
})
.attr("dy", -6)
.text(function(d){
return d.value;
})
this.append("g")
.classed("x axis", true)
.attr("transform", "translate(" + 0 + "," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", -8)
.attr("dy" ,8)
.attr("transform", "translate(0,0) rotate(-45)");
this.append("g")
.classed("y axis", true)
.attr("transform", "translate(0,0)")
.call(yAxis);
this.select(".y.axis")
.append("text")
.attr("x", 0)
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(-50," + height/2 + ") rotate(-90)")
.text("Downtime [Hrs]");
this.select(".x.axis")
.append("text")
.attr("x", 0)
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + width/2 + ",80)")
.text("[Stations]");
// title
this.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "16px")
.style("text-decoration", "underline")
.text("Over Mould");
// limit line
this.append("line")
.attr("x1", 0)
.attr("y1", y(threshold))
.attr("x2", width)
.attr("y2", y(threshold))
.attr("stroke-width", 2)
.attr("stroke", "yellow");
}
d3.json('data.json', function(data) {
plot.call(chart, {data: data});
});
</script>
Data is coming from an external JSON file.
[
{
"key": "ING_SW_CB",
"value": "7"
},
{
"key": "SB_SW_CB",
"value": "15"
},
{
"key": "NG3_SW_CB",
"value": "3"
},
{
"key": "Mould_Close",
"value": "8"
},
{
"key": "Leak_Test",
"value": "9"
},
{
"key": "ML_Load",
"value": "2"
},
{
"key": "Pre_Heat",
"value": "1"
},
{
"key": "Dispense",
"value": "5"
},
{
"key": "A310",
"value": "6"
},
{
"key": "Gelation",
"value": "5"
},
{
"key": "Platen",
"value": "7"
},
{
"key": "Mainline_Unload",
"value": "8"
},
{
"key": "De_mould",
"value": "5"
},
{
"key": "Clean_Up",
"value": "4"
},
{
"key": "Soda_Blast",
"value": "5"
},
{
"key": "RMI",
"value": "15"
},
{
"key": "Miscellaneous",
"value": "5"
}
]
My idea was to create yAxis2 and call it later in the function that plots the chart.
var yAxis2 = d3.svg.axis()
.scale(y)
.orient("right");
this.append("g")
.classed("y axis", true)
.attr("transform", "translate(width,0)")
.call(yAxis2);
When I do this it just draws it in the same place as the first yAxis, when I adjust the transform/ translate it just gets drawn at random positions on the chart, I'm trying to line it up like the left yAxis only positioned on the right. Thanks to all for your input.
Syntax error:
.attr("transform", "translate(width,0)")
To:
.attr("transform", "translate(" + width + ",0)")
plnkr
I have a D3 grouped bar chart with x-axis formed using my x0 scale which has the domain as the data values. As the domain has data values my tick text is also the same data values. I want to change the tick values to data names keeping my scale unchanged as names can be same but data values are unique.
Please help me to change the tick values.
e.g. name: 'New Jersey',
value:'[Calendar]&NewJersey'
I want my axis to be made using the value but the tick text should be name.
http://jsfiddle.net/pragyan88/681q7umb/6
var data = {
chartTitle: "PopulationByState",
xAxisLabel: "State",
yAxisLabel: "Population",
series: [{
name: "< 5 Years",
longName: "Age less than 5 Years",
value: "i",
data: [2704659, 2027307, 1208495, 894368, 3157759]
}, {
name: "5-13 Years",
longName: "Age between 5 to 13 years",
value: "i",
data: [4704659, 6027307, 808495, 1094368, 2157759]
}, {
name: "14-20 Years",
longName: "Age between 14 to 20 years",
value: "i",
data: [1104659, 8027307, 1008495, 394368, 1157759]
}, {
name: "21-40 Years",
longName: "Age between 21 to 40 years",
value: "i",
data: [1404659, 2027307, 4208495, 6027307, 5157759]
}, {
name: "41-65 Years",
longName: "Age between 41 to 65 years",
value: "i",
data: [2404659, 3027307, 7208495, 8027307, 6157759]
}, {
name: ">65 Years",
longName: "Age greater than 65 years",
value: "i",
data: [1404659, 9027307, 4208495, 10027307, 5157759]
}],
categories: [{
name: 'CA',
longName: 'California',
value: '[Calendar]&California'
}, {
name: "TX",
longName: 'Texas',
value: '[Calendar]&Texas'
}, {
name: 'NY',
longName: 'New York',
value: '[Calendar]&NewYork'
}, {
name: "FL",
longName: 'Florida',
value: '[Calendar]&Florida'
}, {
name: "NJ",
longName: 'New Jersey',
value: '[Calendar]&NewJersey'
}]
}
var format = d3.format('.2s');
var returnArray = [];
var canvasWidth = document.getElementById("chart").offsetWidth,
canvasHeight = document.getElementById("chart").offsetHeight;
var margin = {
top: 80,
right: 10,
bottom: 60,
left: 30
},
width = canvasWidth - margin.left - margin.right,
height = canvasHeight - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1, 0.2);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = ['rgb(218,165,32)', 'rgb(41,95,72)', 'rgb(82,82,20)', 'rgb(43,33,6)', 'rgb(96,35,32)', 'rgb(54,69,79)'];
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom")
.tickSize(-height, 0, 0);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"))
.tickSize(-width, 0, 0);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "data: <span style='color:green;'>" + d.data[d.index] + "</span><br/>" + "series: <span style='color:yellow;'>" + d.seriesLongName + "</span><br/>" + "category: <span style='color:red;'>" + data.categories[d.index].longName + "</span>";
});
var legendTip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<span style='color:green;'>" + d.longName + "</span>";
});
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 + ")");
for (var i = 0; i < data.series.length; i++) {
var rgbColor = d3.rgb(color[i]);
var rgbLighterColor = d3.rgb(color[i]).brighter(4);
var id = 'gradient' + i;
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr('id', id)
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%");
gradient
.append("stop")
.attr("offset", "0%")
.attr("stop-color", rgbLighterColor)
gradient
.append("stop")
.attr("offset", "100%")
.attr("stop-color", rgbColor)
}
svg.call(tip);
svg.call(legendTip);
x0.domain(data.categories.map(function(d) {
return d.name;
}));
x1.domain(data.series.map(function(d) {
return d.name
})).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data.series, function(d) {
return d3.max(d.data);
})]);
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("y", 15)
.attr("x", -15)
.style("text-anchor", "end")
.attr("transform", "rotate(-90)")
.attr('class', 'chartLabel')
.text(data.yAxisLabel)
var state = svg.selectAll(".state")
.data(data.categories)
.enter().append("g")
.attr("class", "state")
.attr("transform", function(d) {
return "translate(" + x0(d.name) + ",0)";
});
var bars = state.selectAll("rect")
.data(function(d, i) {
var rArray = [];
for (var x = 0; x < data.series.length; x++) {
rArray.push({
name: data.series[x].name,
data: data.series[x].data,
index: i,
seriesLongName: data.series[x].longName
});
}
return rArray;
})
.enter().append("rect")
.on('click', function(d) {
if (d3.event.ctrlKey) {
if (d3.select(this).style('opacity') == 1) {
returnArray.push({
categoryName: data.categories[d.index].name,
seriesName: d.name,
data: d.data[d.index]
});
d3.select(this).style('opacity', 0.5);
} else {
returnArray.forEach(function(obj, i) {
if (obj.categoryName == data.categories[d.index].name && obj.seriesName == d.name && obj.data == d.data[d.index])
returnArray.splice(i, 1);
});
d3.select(this).style('opacity', 1);
}
} else {
var rect = svg.selectAll('rect');
rect.forEach(function(rec) {
rec.forEach(function(r) {
returnArray = [];
r.style.opacity = 1;
})
});
if (d3.select(this).style('opacity') == 1) {
d3.select(this).style('opacity', 0.5);
returnArray.push({
categoryName: data.categories[d.index].name,
seriesName: d.name,
data: d.data[d.index]
});
}
}
})
.on('contextmenu', function(d) {
d3.event.preventDefault();
alert(d.name);
})
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.attr('class', 'bar')
.attr("width", x1.rangeBand())
.attr("x", function(d) {
return x1(d.name);
})
.attr("y", height)
.attr("height", 0)
.style("fill", function(d, i) {
return "url(#gradient" + i + ")"
});
bars.transition()
.attr('y', function(d) {
return y(d.data[d.index]);
})
.attr('height', function(d) {
return height - y(d.data[d.index]);
})
.delay(function(d, i) {
return i * 250;
}).ease('elastic');
svg.append("text")
.attr("transform", "translate(" + (width / 2) + " ," + (height + margin.bottom / 2) + ")")
.style("text-anchor", "middle")
.attr('class', 'chartLabel')
.text(data.xAxisLabel);
svg.append("text")
.attr("transform", "translate(" + (width / 2) + " ," + "0)")
.style("text-anchor", "middle")
.attr('class', 'chartTitle')
.text(data.chartTitle);
d3.select("svg").on('contextmenu', function() {
var d3_target = d3.select(d3.event.target);
if (!d3_target.classed("bar")) {
d3.event.preventDefault();
alert('I m the body!!')
}
});
d3.select("svg").on('click', function() {
var d3_target = d3.select(d3.event.target);
if (!(d3_target.classed("bar") || d3_target.classed("legend"))) {
returnArray = [];
var rect = svg.selectAll('rect');
rect.forEach(function(rec) {
rec.forEach(function(r) {
r.style.opacity = 1;
})
});
}
});
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar {
fill: steelblue;
}
.x.axis path {
display: none;
}
<section class="container">
<div class='watermark'>
<div id="chart" style="width:300px;height:400px;"></div>
</div>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
/
Thanks in advance.
According to the json structure of the the input data in question, using the following line for x-axis helped:
svg.append("g")
.attr("class", "x axis")
.attr("id", "xaxis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll('text')
.text(function (d,i) {
return data.categories[i].name;
})